In Linux, there is a straightforward way to copy files. Yes, you guessed it right. There is a specific utility for this purpose named
To copy files using the cp command, you just have to mention the location of a file that needs to be copied and the destination:
cp [path/to/file] [destination]
But that was just copying a single file but what about copying multiple files, directories, etc? Well, I got you covered as always!
How to rename and copy files in Ubuntu
This is probably what I use daily as I often make file copies with new names.
While it may sound complex, you just have to append the new file name with the destination:
cp [path/to/file] [destination/New_File_name]
For example, If I want to copy the file named
Hello.txt at Downloads renamed as
World.txt, I'd have to follow the given command:
cp Hello.txt Downloads/World.txt
How to copy multiple files in Ubuntu
This is what you will end up using the most as generally most of the users will copy more than one file and trust me it is pretty easy than you think it might be.
You just have to append multiple files with the cp command separating them with space and that's it:
cp file1 file2 file3 Destination/
Similarly, you can also specify the file extension as a wildcard to copy every file associated with that extension.
cp File_Directory/*extension Target_Directory/
For example, If I want to copy all the mp3 files from
Downloads directory to the
Music directory, I will have to use the given command:
cp Downloads/*.mp3 Music/
How to copy files recursively in Ubuntu
Recursively means it will copy the entire directory with every sub-directory present and will keep on till the maximum depth.
To do that, you will have to use the
-R option and append the directory that needs to be copied recursively:
cp -R Target_Directory/ Destination/
For example, if I want to copy every file present in the
Downloads directory including files of the subdirectory to the directory named
Documents, I have to use the given command:
cp -R /Downloads /Documents
And as you can see, it copied the entire Downloads directory at the desired location.
-n to not overwrite an existing file while copying. You can also use the interactive mode with option
How to preserve file attributes while copying
As you can clearly see in the above image that the file owner and timestamp were manipulated in the copied file.
And to preserve such attributes, you'd have to use the
-p option while copying files:
cp -p Source_Directory/ Destination/
But what about ownership? Well, you have to use superuser privileges (sudo) to preserve ownership:
In this guide, I explained how you can copy files in Ubuntu using the cp command, and if you want to learn more about the cp command, here are some practical examples of the cp command.