How to Copy a Directory in Linux Command Line

Question: How do I copy a directory and the files inside it to another directory in Linux command line?

Answer: You probably already know that you can use cp command to copy files in Linux command line. You can use the same cp command with the recursive option to copy a folder with its content to another folder.

All you got to do is to use the command in this fashion:

cp -r source_directory destination_directory

And now if you ls on the destination directory, it should have the entire source directory inside it.

The -r option allows the recursive option. This means the entire content of the directory including its tree structure will be copied to the destination.

Note:

Couple of things to note here. If the destination directory doesn’t exist, it will be created up to one level (explained in the next section). However, it will now copy the contents of the source directory, not the source directory itself.

For example, if you do this:

cp -r source_directory non_existing_directory

The non_existing_directory will be created with the content of the source_directory but it won’t have the source_directory inside it. Just the files of source_directory will be copied.

For example, if you try to use cp -r source_dir dir1/dir2/dir3 but dir2 and dir3 don’t exist, it won’t create the nested directory structure and the command fails.

One last tip to keep things short. If you use the -a option along with the -r option, it will preserve the original file information such as the owner of the files, modification date etc. It will archive the directory to the new location instead of creating it afresh.

Share this:

Other Linux Command Tips

About Abhishek Prakash

I am a software developer by profession and a Linux user by passion. I also co-founded It's FOSS. Linux Quick Tips is my quick notebook where I share quick Linux command tricks, some basic and some advanced.