How to Copy Files in Linux Using the Cp Command

Learn how to copy files in Linux using the cp command. This comprehensive guide covers everything from the basic syntax to advanced options, with examples.

How to Use cp command

The general syntax for the cp command is as follows:

cp [OPTIONS] SOURCE... DESTINATION

The SOURCE can contain one or more files or directories as arguments, and the DESTINATION argument can be a single file or directory .

  • When the SOURCE and DESTINATION arguments are both files, the cp command copies the first file to the second one. If the file doesn’t exists the command creates it.
  • When the SOURCE has multiple files or directories as arguments, the DESTINATION argument must be a directory. In this situation, the SOURCE files and directories are moved to the DESTINATION directory.
  • When the SOURCE and DESTINATION arguments are both directories, the cp command copies the first directory into the second one.

To copy files and directories, you must have at least read permissions on the source file and write permission on the destination directory. Otherwise, a permission denied error is shown.

Copying Files with cp Command

The most basic scenario of using cp is to copy a file in the current working directory. For example, to copy a file named file.txt to file_backup.txt you wound run the following command:

cp file file_backup

or

cp file{,_backup}

To copy a file to another directory, specify the absolute or the relative path to the destination directory.

When only the directory name is specified as a destination, the copied file have the same name as the original file.

In the following example we are copying the file file.txt to the /backup directory:

cp file.txt /backup

#command #linux

How to Copy Files in Linux Using the Cp Command
775.60 GEEK