Written by , Updated on February 10, 2021

As a Linux user, you must be well acquainted with Linux cp command. Which is used to copy files from one directory to another directory.

This tutorial will explain you to how to copy a file to multiple directories in a single command.

By default we can copy a file to single destination directory in one command. For example, copy a file tecadmin.txt from home directory to two different directories, uses commands like:

cp -v ~/tecadmin.txt  /backup/dir1/ 
cp -v ~/tecadmin.txt  /backup/dir2/ 

How to Copy a File to Multiple Directories in Linux General Articles

Now, use the following command to copy the same file to both destination directories in a single command. Here we use echo command followed by the the destination directory names. Then pipe the results to the xargs commands, which will take directory names as input and pass it to the cp command.

echo /backup/dir1/ /backup/dir2/ | xargs -n 1 cp -v ~/tecadmin.txt 

How to Copy a File to Multiple Directories in Linux General Articles

Next, verify that the source file is copied to both destination directories. Just use ls command to list file at both locations.

ls -l /backup/dir1/tecadmin.txt 
ls -l /backup/dir2/tecadmin.txt 

You will find that the same file is copied to both destinations in single command.

While copying file to 2-3 directories, you can do it easily with multiple commands. But think, if you have to copy this to large number of directories at a time. For example, I have a WHM/cPanel server with large number of account and want to place a file to each accounts public_html directory. We can do this in single command as:

echo /home/*/public_html/ | xargs -n 1 cp -v ~/tecadmin.txt 

[output]
'/root/tecadmin.txt' -> '/home/user1/public_html/tecadmin.txt'
'/root/tecadmin.txt' -> '/home/rahul/public_html/tecadmin.txt'

Hope this tutorial help you understand to copy file to multiple directories in a single command.