How to Copy / Move Files and Directories in Linux with “cp” and “mv” commands

Copy Files and Directories

The cp command will copy files and directories or copy multiple sources to a destination directory. The basic syntax of the cp command is:

# cp [options] source destination

If you have multiple files/directories to be coped to a destination directory, use the below command syntax.

# cp [options] source1 source2 [...] destination_directory

Common options used with the cp command, include:
-a – archive, never follow symbolic links, preserve links, copy directories recursively
-f – if an existing destination file cannot be opened, remove it and try again
-i – prompt before overwriting an existing file
-r – copy directories recursively

These examples show typical invocations of the cp command with descriptions of what they do.

Example 1

Copying a single file to a destination directory:

$ cp data.txt /var/tmp/

Example 2

Copying multiple files to a destination directory:

$ cp data.txt file.csv /var/tmp/

Example 3

Copying a directory (and it’s contents) recursively:

$ cp -r /etc/ /var/tmp/backup/

Moving Files and Directories

The mv command will move or rename files or directories, or can move multiple sources (files and directories) to a destination directory. The basic syntax of the mv command is:

# mv [options] source destination

To move multiple files/directories into a destination, use the below syntax.

# mv [options] source1 source2 [...] destination

Common options used with the mv command:
-f – do not prompt before overwriting
-i – prompt before overwrite
-u – move only when the source file is newer than the destination file or when the destination file is missing

Note: that if the destination exists, it will be overwritten unless the -i option is used.

If a file or directory is moved to a new name within the same directory, it is effectively renamed. For example, this would rename a file from oldname to newname.

$ mv -i oldname newname
Related Post