cp -r Linux Command to Recursively Copy Files and Directories

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


% 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

Note: The cp -r command will silently overwrite the files at the destination directory with the corresponding files from the source directory.

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
cp -r command linux

Facing issues? Have Questions? Post them here! I am happy to answer!

Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap