Copying a file from one directory to another is something that everyone should know. It is pretty basic stuff which even a Linux newbie can do with a little information and we don’t have to discuss the latest operating systems in which the task is a child’s play. Just like Macand Windows, you can easily copy a file from GUI command by right-clicking the file and then choosing the copy option.
But, what if you want to copy a file to different directories? You can just do this using a single command line.
Usually, we would use cp command to copy files on a Linux machine. But, this command is restricted to copy a single file to a specific directory. If you want to copy a file to more than one destination, you have to look for an alternative.
In Linux, there is a command to do anything. So, we when we explore deep over a command, we can a do a lot of things using it. In the case here, we are going to use “echo”.
The command is basically used to write or print on the screen. But, we can use this command to copy a file also and it provides additional options. Before executing this command, it is better to understand how the command works.
Below is the syntax of the command we are using now.
echo dir_1 dir_2 dir_3 | xargs -n 1 cp file1
In the case here, we want to feed output of echo command as input to xargs command. And to do this, we use pipe symbol ( | ) which feeds output from one command as input to another. The xargs command will run the cp command three times, each time appending the next directory path piped to it from the echo command on to the end of the cp comAmand. There are three arguments being passed to xargs , but the -n 1 option on the xargs command tells it to only append one of those arguments at a time to the cp command each time it’s run.
Got it?
Below is the example of the command.
echo dir_1 dir_2 dir_3 | xargs -n 1 cp copythisfile.txt