Sometimes you may need to copy file to multiple folders or directories. It is very easy to do this using cp and xargs command. In this article, we will look at how to copy file to multiple directories.
How to Copy File To Multiple Directories
By default, cp command alone cannot be used to copy file to multiple directories. Let us say you want to copy a single to the following different directories. Typically, we will to execute them separately using cp command.
Here is an example,
$ sudo cp /home/ubuntu/file.txt /home/user1 $ sudo cp /home/ubuntu/file.txt /home/user2 $ sudo cp /home/ubuntu/file.txt /home/user3
If you want to copy single file to a large number of directories this can be very tedious.
In such cases, we have to pass the list of destination folders to xargs command which will use them to construct and execute cp command for each destination folder.
Also read : How to Install Joomla in Ubuntu
Here is how we can copy file to the above 3 destination folders using a single command.
$ xargs -n 1 cp -v /home/ubuntu/file.txt<<<"/home/user1/ /home/user2/ /home/user3/" OR $ echo "/home/user1/ /home/user2/ /home/user3/" | xargs -n 1 cp -v /home/ubuntu/file.txt
In the above command “-n 1” argument tells xargs to use at the most 1 argument at a time to construct the “cp – v /home/ubuntu/file.txt” command for each argument. xargs command basically loops through the standard input string of destination folders and creates separate cp command to copy the file to each destination folder individually. It gives the following output
/home/ubuntu/file.txt -> /home/user1/file.txt /home/ubuntu/file.txt -> /home/user2/file.txt /home/ubuntu/file.txt -> /home/user3/file.txt
That’s it. As you can see it is very easy to copy file to multiple folders in Linux.
Also read : How to Install MySQL in Ubuntu
Related posts:
How to Use Key-Value Dictionary in Shell Script
How to Limit User Commands in Linux
How to Check if Port is Open or Closed in Linux
How to Fix "mv: Argument List too Long" Error
Install KeepAlived in CentOS 7 from source
Linux Rename File Starting with Dash
How to Rename Multiple Files in Linux
How to Create Empty Disk Image in Linux

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.