How to Copy Directories and Files on a Linux Server

Contents

If you need to copy files or directories between 2 different Linux servers, please see this article instead.

Copy a Directory

Suppose you have a directory /opt/test and you want to copy it as /opt/test2. Run in the terminal:

cp -pPrv /opt/test /opt/test2

, where

  • -p – preserve the owner/group, mode (i.e. access permissions), and timestamp.
  • -P (--no-dereference) – do not follow symbolic links in the source directory.
    The symbolic links will be copied as symbolic links.
  • -r (-R, --recursive) copy the directory with subdirectories recursively.
  • -v (--verbose) – shows all the progress in the terminal.

For more details:

Please notice: For the command above:

  1. The existence of the destination directory matters:
    • If the destination directory /opt/test2 does not exist, the command will copy /opt/test as /opt/test2.
    • If the destination directory /opt/test2 exists, the same command will copy /opt/test as /opt/test2/test.
      This means it will copy the source directory into the existing destination directory as a subdirectory.
  2. Trailing slashes for the source and destination directories do not matter. Whether you have them or not, the result will be the same.
    In the example above, if the source directory is /opt/test or /opt/test/ and if the destination directory is /opt/test2 or /opt/test2/, does not matter. The copy command will work the same.

Copy a File

To copy a file:

cp -pv /opt/test/a.txt /opt/test2/b.txt

This will copy the file /opt/test/a.txt as /opt/test2/b.txt.

Here:

  • -p – preserve the owner/group, mode (i.e. access permissions), and timestamp.
  • -v (--verbose) – shows all the progress in the terminal.

For more details:

If you need to copy a file to a directory:

cp -pv /opt/test/a.txt /opt/test2/

This will copy the file /opt/test/a.txt to the directory /opt/test2/.

Please notice: The trailing slash for the destination directory matters for copying a file to a directory.

For example, without the trailing slash at the destination, the command

cp -pv /opt/test/a.txt /opt/test2

will interpret /opt/test2 as a file name, not a directory name. And will try to copy the file /opt/test/a.txt to the file /opt/test2.

Sergei Korolev
Sergei Korolev
Web developer and the author of all articles on this site. With over 25 years of programming experience, he has specialized in web programming for more than 19 years. He is a Zend Certified Engineer in PHP 5.3. He is available for hire at a rate of $60 USD per hour. You can see his resume here. Please contact him via this contact form to get a quote. He currently lives in Belgrade, Serbia.

Leave a Reply

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