If you want to copy a file or a directory from one path to another using the Linux Terminal, you can make use of the cp (copy) command.
But, when you have to copy directories that in them have multiple other files and directories, then you need to make use of the -r option to copy them recursively.
Let's take a look at an example.
cp -r Command Syntax:
cp -r <source-directory> <destination-directory>
cp -r command example
cp -r dir1 dir2
Let's see whats there in dir2
% ls dir2
dir1
% cd dir1
ls -ltrh
% ls -ltrh
total 0
drwxr-xr-x 7 c2ctechtv staff 224B Aug 4 13:58 temp
-rw-r--r-- 1 c2ctechtv staff 0B Aug 4 13:58 data.csv
-rw-r--r-- 1 c2ctechtv staff 0B Aug 4 13:58 2023.txt
-rw-r--r-- 1 c2ctechtv staff 0B Aug 4 13:58 data.txt
More Examples:
If you want to see the process of the cp -r command, and the -v flag to the command.
% cp -rv dir1 dir2
dir1 -> dir2
dir1/temp -> dir2/temp
dir1/temp/a -> dir2/temp/a
dir1/temp/c -> dir2/temp/c
dir1/temp/d -> dir2/temp/d
dir1/temp/e -> dir2/temp/e
dir1/temp/b -> dir2/temp/b
dir1/data.csv -> dir2/data.csv
dir1/2023.txt -> dir2/2023.txt
dir1/data.txt -> dir2/data.txt
If you want to preserve the file's attributes such as timestamps, ownership makes use of the -p flag.
cp -rp dir1 dir2
To copy the hidden files and folders as well,
cp -rp dir1/. dir2
To exclude cetain files.
cp -rp dir1 dir2 --exclude=data.csv

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!