Linux

Copy a directory with all files – Linux

September 13, 2021

Copy a directory with all files – Linux

The cp command is used for copying, but how do we copy a directory with all the files inside it? See this article

Copy a directory with all files cover

How to copy all files and directories from a directory?

When we use the cp command on a file, for example:

cp a.txt b.txt

We see that the b.txt file is created in our current directory, with the same content as a.txt

So the cp command works perfectly.

But when we use the same cp command on a directory, like this:

cp dir1 dir2

We received a warning, which says:

cp: -r not specified; omitting the ‘dir1’ directory

cp: -r not specified; omitting the ‘dir1’ directory.

And nothing is created, it looks like the copy command is not working properly, what should we do then?

Well, if you see the warning message it says the -r wasn’t specified.

So that’s exactly what our command lacks!

The -r option means recursive, that is, it will copy directories and subdirectories.

So if we repeat the command like this:

cp -r dir1 dir2

Now, dir2 will be created exactly like dir1, with all its files and subdirectories, simple right? 😀

And here’s a tip for your future commands, usually the -r option always does the same function.

Make your command recursive somehow.

For example: if it’s a change permissions command, chmod, all the directories, and files that are within the permissions you changed will change too.

Another important point is that it is always good to know what the parameter/option means, that is, its English word.

Knowing this we can remember the command action faster, without having to consult manuals/Google.

Conclusion

To copy a directory with all files, just add the -r option to the cp command.

This way you will have a faithful copy of the entire content of the target directory, in another place in the system of your choice.

And that’s it for today, until the next post!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x