How to copy a file to multiple directories on Linux?

The cp command on Linux is used to copy a file from one place to another. And using the command options, you can do a wide variety of work with this command, such as copying a large number of files simultaneously to a destination folder. However, let’s say you want to copy a single file to different locations. Certainly, this is not possible with just the cp command, we will have to use it along with the xargs command with the help of the pipe feature in the Linux terminal.

Also read: Copy a large number of files using the terminal.

Copying files with the cp command

Normal use of the cp command would be :

cp {options} file(s) /path/to/destination

Let’s say I want to copy a file named LFD.txt into two directories named Dir1 and Dir2, we can do this one by one, by typing :

cp -v LFD.txt Dir1
cp -v LFD.txt Dir2
Copying File One By One Into Different Directories
Copying Files One By One Into Different Directories

Copy a file into multiple directories

Now, to copy the file simultaneously, all you need to do is type the command like this :

echo /home/aadesh/Test/Dir1 /home/aadesh/Test/Dir2 | xargs -n 1 cp -v /home/aadesh/Test/LFD.txt
Copying A File Into Multiple Directories Simultaneously
Copying A File Into Multiple Directories Simultaneously

What the above command does is mentioned below :

  • The path to directories Dir1 and Dir2 are echoed and piped as input to the xargs command.
  • xargs will execute the cp command twice (or as many times as the number of directories)
  • The -n 1 option tells the xargs command to use one argument per command and forward to the cp command.
  • cp -v is the copy command along with a verbose flag so that you can see a progress bar while copying the file.

Summary

You can read more about the cp, echo and xargs command by reading their manual pages. You can access them by typing :

# To read more about cp command
man cp

# To read more about the echo command
man echo

#To read more about xargs command
man xargs

References