The ultimate guide to copying files and directories in Linux
Copying files and directories in Linux can be done with the cp command, which takes two arguments—the file or directory you want to copy (or move) and the location to copy it to—and with the mv command, which takes two arguments—the file or directory you want to rename and the new name for it. You can also delete files and directories in Linux with the rm command, which does not require any additional arguments.
Copy files using cp -r
The cp command stands for copy and is used to copy one or more files from one place to another. To use cp, you will need the following:
- The filename of the file(s) that you want to copy. For example, if we wanted to get a list of all the text documents on our computer we would type:
Copy directory structure with cp -a
To copy a directory structure from one location to another, you will need to first make sure that your destination is empty or has enough space. To do this, you can use the du command. For example: du -h –max-depth=1 . This will show the size of the current directory (in human readable format) and how many levels deep it is. If there is enough space for your desired copy, then execute the following command: cp -a . If you are creating a new folder at the destination point, you would use mkdir instead of cp -a . The following commands will also help with copying: mv , rm , rsync , tar
Copy files recursively with find . -exec cp -v {} \;
When using the find command, we can use the -exec option followed by a command. This is useful for executing commands on all of the items found. For instance, if we wanted to copy all of our .txt files from one folder to another, we could run:
find . -name *.txt -exec cp {} \; (Note that this will not prompt you for confirmation.)
Copy an entire tree with rsync
If you want to copy an entire tree, you can use the rsync command. It’s as simple as this:
1 $ rsync -avh –delete . ~/destination