Creating And Removing Files and Directories

Creating a Directory: mkdir

  • Create a new directory in an existing directory

    $ mkdir /tmp/a-directory
    
  • Cannot create a directory inside a directory that doesn’t exist

    $ mkdir /tmp/an/entire/hierarchy
    mkdir: cannot create directory ‘/tmp/an/entire/hierarchy’: No such file or directory
    
  • mkdir -p

    $ mkdir -p /tmp/an/entire/hierarchy
    

Creating a File: I/O redirection

Create a file (or overwrite if it exists)

$ echo hello > /tmp/a-file-containing-hello
$ cat /tmp/a-file-containing-hello
hello

And permissions? I didn’t say how I want these! 🤨

$ ls -l /tmp/a-file-containing-hello
-rw-rw-r--. 1 jfasch jfasch 6 Mar  9 18:56 /tmp/a-file-containing-hello

Default Permissions: umask

Append to an existing file (or creating, if it doesn’t exist)

$ echo sweetheart >> /tmp/a-file-containing-hello
$ cat /tmp/a-file-containing-hello
hello
sweetheart

Creating an Empty File: touch

$ touch file.txt

Removing A File: rm

Remove a file

$ rm /tmp/a-file-containing-hallo

Remove a file, but no permissions

$ rm /etc/passwd
rm: remove write-protected regular file '/etc/passwd'? y
rm: cannot remove '/etc/passwd': Permission denied

Remove a file, suppressing the stupid question

  • ⟶ still fails with /etc/passwd because owned by root)

  • Succeeds though if owned by myself but not writeable

$ rm -f /etc/passwd
rm: cannot remove '/etc/passwd': Permission denied

Removing A Directory: rmdir, rm -r

  • rmdir: remove directory - provided that it is empty

    $ rmdir /tmp/a-directory
    
  • rmdir fails if directory not empty

    (remember, we recently created /tmp/an/entire/hierarchy)

    $ rmdir /tmp/an/entire
    rmdir: failed to remove '/tmp/an/entire': Directory not empty
    
    • Solution 1 (no!): bottom up

      • Use rm to remove files from leaf directories ⟶ make them empty

      • Use rmdir to remove empty leaf directories

      • Repeat one leavel up until all is done

    • Solution 2 (better): shorthand for Solution 1 - rm -r

      $ rm -r /tmp/an/entire