If you need to copy files or folders 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:
- Run the command “
man cp” in the terminal.
Or see the man page online. - See the GNU command description (
cpis a GNU utility)
Please notice: For the command above:
- The existence of the destination directory matters:
- If the destination directory
/opt/test2does not exist, the command will copy/opt/testas/opt/test2. - If the destination directory
/opt/test2exists, the same command will copy/opt/testas/opt/test2/test.
This means it will copy the source directory into the existing destination directory as a subdirectory.
- If the destination directory
- 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/testor/opt/test/and if the destination directory is/opt/test2or/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:
- Run the command “
man cp” in the terminal.
Or see the man page online. - See the GNU command description.
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.