How to copy a file with one command to several directories in Linux

Copying a file to Linux is simple, whether using the command line or graphically. However, some users prefer the command line for almost all tasks. The command line offers not only a simple, but also a faster way to complete the task. Cp is a command on Linux that is used to copy a file from one place to another. But what if we need to copy the file to several places? There is a way to show how to achieve this on Linux.

We ran the commands and procedures mentioned in this article on Debian 10, but they will work on any other Linux distribution.

Let’s first see how we can use the cp command to copy files from one place to another. The general syntax for copying files using the cp command is:

$ cp ~[/location/sourcefile] ~[/destinationfolder]

An example of this is copying testfile1 from the Documents directory to the Downloads directory. To do this, I ran the following command in the terminal:

$ cp ~/Documents/testfile1 ~/Downloads/

Now that we need to copy the file to several places, we need to run the command several times. For example, in the following example, we copy testfile1 from Documents to two different locations, i.e. Downloads and desktop. To do this, we need to run the cp commands in the Terminal twice:

$ cp ~/Documents/testfile1 ~/Downloads/

$ cp ~/Documents/testfile1 ~/Desktop/

Copy two files

Copy a file to multiple locations using the echo command

Copying a file to two places using the cp command is still valid, but let’s assume that we need to copy the file to four, five or more places. in this case, we have another solution using the echo command. The syntax of the command is as follows:

$ echo [destination1] [destination2] [destiantion3]..... | xargs -n 1 cp [/location/sourcefile]

The echo command is commonly used in shell scripts to display a message or display. But here, in this example, we will use it to pass the output to the xargs command through | symbol. Xargs will receive the input three times from the echo command and perform cp operations three times by copying the test file to 3 different places. The n flag in the above command tells cp to accept one argument at a time.

Note that this command will overwrite an existing file with the same name in the destination directory. Therefore, it is better to back up an important file.

In the following example, we use this command to copy testfile1 from the Documents directory to three different directories: Desktop, Downloads, and Music. To do this, we ran the following command:

$ $ echo [~/Desktop] [~/Downloads] [~/Music] | xargs -n 1 cp [/location/sourcefile]

Copy the file to several places

That is all there is to it! Now we have learned how to copy a file with one command to several directories. So now you do not need to write several commands to perform the simplest task of copying one file to several places.

How to copy a file with one command to several directories in Linux

Sidebar