infoLinux

Copying files in Linux using cp Command

The command cp stands for – copy.

It is used to copy files in the file system. The basic syntax is

$ cp <source> <destination>

The <source> is the existing file’s name. And the <destination> is a new file name. We can also use relative/absolute paths in <source> and <destination>.

For example:

In the example, we have created a copy of ‘doc’ and named it as ‘newdoc’. If a file named ‘newdoc’ already exists, then the file will be simply over written. So, we should check first if the new file name is not a existing file name.

To copy file to a different directory

In the previous example, we have copied files in the same directory. But if we want to copy a file in the present directory to a different directory, we need to simply write the relative/absolute path in the <destination> section.

For example:

In the example we’ve copied the ‘newdoc’ file from our present directory to /home/infolinux/ directory.

If we want to copy files from a different directory, we need to give the absolute path of the file in the <source>.

Usage with Common Options of cp Command:

  1. cp <source> <destination> to copy file from source to destination
  2. cp -r <source> <destination> to copy a whole directory recursively to destination directory
  3. cp -backup <source> <destination> to backup existing file before overwriting it
  4. cp -i <source> <destination> asks for confirmation
  5. cp – I <source> <destination> creates a hard link (note that, this doesn’t create an actual copy)
  6. cp -p <source> <destination> preserves attribute of a file

cp -u <source> <destination> copy only when the <source> file is newer than the destination file, or the destination file is missing

Leave a Reply

Your email address will not be published. Required fields are marked *