Files

Perform standard file operations

Create

Create a new empty file with touch:

        $ touch cats.txt
        
      

Creates cats.txt

To create a directory instead, use mkdir. For example, mkdir animals to create the animals directory.

You can also create files and directories within other directories:

        $ mkdir animals/cats
        
      

Creates the cats directory within the animals directory

If the animals directory doesn't exist, the previous command will fail. To create both directories at the same time, use the -p flag:

        $ mkdir -p animals/cats
        
      

Creates the animals and cats directories

View contents

Use cat to print the contents of a file:

        $ cat dogs.txt
        
      

Prints the contents of dogs.txt

Remove

Remove files and directories using the rm command. Use rm dogs.txt to remove the dogs.txt file. To remove a directory, use the -r flag:

        $ rm -r animals/
        
      

Removes the animals directory

Move, rename, and copy

The mv command can move and rename files. To move dogs.txt into the animals directory, use mv dogs.txt animals/. Move multiple files into the same directory by using mv dogs.txt cats.txt animals/.

You can also specify a pattern:

        $ mv *.txt animals/
        
      

Moves all .txt files into the animals directory

Renaming files uses a similar syntax. To rename dogs.txt to cats.txt, use:

        $ mv dogs.txt cats.txt
        
      

Be careful! If the cats.txt file already exists, it will be overwritten.

The cp command is used to copy files and the syntax is very similar to that of the mv command. In fact, in all the examples above, you can simply replace mv with cp to copy the file(s) instead of moving/renaming them.

If you want to copy a directory, you must use the -r flag.