How To Copy Files and Directories In Linux?

All Linux distributions provide the cp command as a copy command for the files and directories. The cp name comes from the copy . The copy command can be used to copy files and folders easily. Files and folders can be copied using different options of copy command like recursive, verbose, preserving attributes, etc. In this tutorial, we examine different usage examples of the copy command for files and directories.

Copy Command Syntax

The syntax of the copy command is like below.

  • OPTION is used to specify different options for the copy command. The OPTION is optional.
  • SOURCE is the single or more source files or directories.
  • DESTINATION is the destination file or folder.

Copy Command Help

Copy command help information can be listed by using the --help option like below.

$ cp --help
Copy Command Help

Copy Command for Files

A file can be copied simply by providing the source and destination file names. In the following example, we copy the file named “db.txt” into “db_bak.txt” file. Directories can not be copied like below as they require a recursive option which is explained in the next section.

$ cp db.txt db_back.txt

Copy Command Recursively

Directories and their contents can be copied by using the recursive option. The -r is used to copy recursively the specified directories and all of its contents. These contents may other files or directories. In the following example we copy the directory “/home/ismail/db” into “/home/ismail/db_bak”.

$ cp -r /home/ismail/db /home/ismail/db_bak

Copy Command Verbose

By default, the copy command does not provide detailed information about the copy operation and copied files. The verbose option -v can be used to copy verbosely to print all copied files or directories.

$ cp -r -v /home/ismail/db /home/ismail/db_bak

Copy Command Preserving Attributes

During the copy operation of files and directories, the file or directory attributes are not copied by default. We can enable the file and directory attribute copy for the copy command by using the -p .

$ cp -r -p /home/ismail/db /home/ismail/db_bak

Copy Command Force

The copy command uses the force option -f to “if an existing destination file cannot be opened, remove it and try again”.

$ cp -r -f /home/ismail/db /home/ismail/db_bak

Copy Command Interactively

Especially copying directory contents there may be a lot of files and directories. Some of them may also exist in the destination directory and we may not overwrite the destination file. We can copy files and directories interactively by approving every copy operation. The -i is used to copy command interactively.

$ cp -r -i /home/ismail/db /home/ismail/db_bak
See also  Difference Between "yum update" and "yum upgrade" Commands

Leave a Comment