Moving and Copying Files and Directories

NOTE: this website is out of date. This is the course web site from a past quarter. If you are a current student taking the course, you should visit the current class web site instead. If the current quarter's website is easily reached, it may be accessible by visiting this link instead. Please be advised that courses' policies change with each new quarter and instructor, and any information on this out-of-date page may not apply to you.

Written by Chris Gregg, with modifications by Nick Troccoli

Click here for a walkthrough video.

To copy a file in linux, you use the cp command:

$ cp SOURCE_FILE DESTINATION

The SOURCE_FILE is the file you want to copy, and the DESTINATION is where you want to copy it to. DESTINATION can be a path with or without a filename. If you leave the filename off, the file will have the same name as the original.

Example:

$ cp assign0/hello.c assign1/hello.c
$

The command above copies the hello.c file from the assign0 directory into the assign1 directory. If assign1 already exists as a directory, you could make the command shorter as follows:

$ cp assign0/hello.c assign1
$

If the assign1 folder did not already exist, a copy of the hello.c file would have been made in the current directory, and it would have been named assign1 -- probably not what you wanted to do. So, you have to be careful when copying.

On myth, your profile has been set up to warn you if a file already exists. This is not the case on many other Linux systems, so be careful! On other systems, copying a file with cp replaces a file with the same name in that location without asking you or telling you that it has removed the original file (permanently).

To copy an entire directory, use the -r (recursive) option for cp:

$ cp -r assign0 assign1
$

This will copy the entire assign0 directory into the directory called assign1. If assign1 does not exist, the cp command will create it.

The mv command moves files in a similar way to cp. It also doubles as a way to rename a file:

$ mv originalFile newFile
$

This renames originalFile to have the name newFile. You can move entire directories without a recursive flag:

$ mv directory1 directory2
$

Again, on myth, you will be asked before overwriting files with mv, but this is not normally the case on other systems, so be careful!