If you are new to the Linux command line, you probably have this question in mind: How do I copy a directory and the files it contains into another directory on the Linux command line?
You probably already know that you can use the cp command to copy files to Linux. Do you know that you can use the same cp command to copy a folder on the Linux command line?
Ha! You already tried, and maybe you received this error:
cp: -r not specified; omitting directory 'test_dir'
Let me show you one or two things about copying directories in Linux.
Copy directory in Linux command line
You can use the cp command but with the recursive -r option to copy a folder with its contents to another folder. The error mentioned above also suggests that the -r option was lost.
All you have to do is use the command this way:
cp -r source_directory destination_directory
And now, if you use the ls command in the destination directory, you should have the entire source directory inside.
The -r option allows the recursive option. This means that all directory content, including its subdirectories, everything in the directory will be copied to the destination.
Few things to keep in mind when copying directories in Linux
Here are a couple of things to keep in mind and tips on how to copy folders.
- If the destination directory does not exist, it will be created up to a level (explained in the next section). However, you 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-existent directory will be created with the content of the source directory but will not have the source directory inside. Only the source_directory files will be copied. It would be like non_existing_directory will be a replica of source_directory.
sameer@t4tech:~$ ls test_dir sameer@t4tech:~$ cp -r test_dir new_dir sameer@t4tech:~$ tree . ├── new_dir │ ├── c.xyz │ ├── myzip1.zip │ └── myzip2.zip └── test_dir ├── c.xyz ├── myzip1.zip └── myzip2.zip 2 directories, 6 files
- You cannot use the previous command to create a nested directory structure.
For example, if you try to use cp -r source_dir dir1 / dir2 / dir3 but dir2 and dir3 do not exist, it will not create the nested directory structure, and the command will fail.
One last tip to keep things short. If you use the -a option together with the -r option, it will retain the original file information, such as file permissions, etc. You will archive the directory in the new location instead of creating it again.
This article explained the cp command that is used for copying files under Linux and Unix-like systems.