cp command to copy file and directory in Linux
cp command is helpful to make the same copy of a file either in working directory or somewhere else. cp command can also be used to make a copy of the directory.
cp to work within your working directory
$cp file1 file2
In above command, file1 is original file and file2 is created using cp command
cp to work outside the working directory
$cp path/to/source/file1 path/to/destination/
If you want to rename your original file then use cp, as follows
$cp path/to/source/file1 path/to/destination/file2 %% file2 is new of your parent/original file
To copy more than one file use cp as follows
$cp file1 file2 file3 path/to/destination/
cp to copy a whole directory
$cp -r path/to/source/directory/ path/to/destination/
If you want to rename your directory then use cp as follows
$cp -r path/to/source/directory/ path/to/destination/directory2
Copy a file to multiple directories in Unix or Linux
To perform this task you need to use xargs command, which constructs argument list(s) and execute utility such as cp or mv. This task can be performed using following approaches and syntax are as follows:
- Using echo command
$echo “dir1 dir2 dir3” |xargs -n 1 cp -v filename
- -n 1– tells xargs to use at most one argument per command line and send to the cp command.
- cp– used to copying a file.
- -v– enables verbose mode.
Here, is an example to make it more clear, In this example you will see that man.png is transferring to job1 and job2 directories.
2. Without echo command
$xargs -n 1 cp -v filename<<<“dir1 dir2 dir2”
$for source_directory in destination_directory1, destination_directory2 ;do cp -v filename $source_directory; done
Copy multifiles from multi source to single destination
Sometimes we need to copy different files from different directories into a singles destination. This task can be performed using the following syntax:
- cp to copy only one file from each directory
$cp path/to/dir_1/filename path/to/dir_2/filename path/to/dir_3/filename path/to/destination/dir
2.cp to copy more then one file from each directory
$cp path/to/dir_1/filename_1path/to/dir_1/filename_2 path/to/dir_2/filename path/to/dir_3/filename path/to/destination/dir
In above syntax we are copying two files from directory 1