Home Linux How to Copy A File to Multiple Directories in Linux With a...

How to Copy A File to Multiple Directories in Linux With a Single Command

Copying a file is absolutely a very easy task to do in every modern operating system, including Linux. Just like Windows and Mac, you can copy a file easily from GUI command by right-clicking the file and choose the copy option.

However, what if you want to copy a file to multiple directories with a single command. You can only do this using command line.

Normally, we would use cp command to copy a file in Linux. But, this command can only be used to copy a file to a specific directory. If you think of to copy a file to more than one destinations, you have to look for another alternative.

Fortunately, Linux comes with so many commands. When we explore deeper over a command, we can a do lot of things using it. In this case, we are going to talk about “echo”.

This command is basically used to write on the screen. But, we can also use this command to copy a file with additional options. Before executing the command, it’s better to understand how the command works.

Below are the syntax of the command we are going to use.

echo dir_1 dir_2 dir_3 | xargs -n 1 cp file1

In this case, we want to feed the output of the echo command as input to the xargs command. To do this, we use the 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 command. 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

This page may contain affiliate links, which help support bettertechtips.com. Learn more


Please enter your comment!
Please enter your name here

Recent Posts