How to copy a single file to multiple directories in Linux or Unix

If I want to copy a single file into three locations (directories), by using a single cp command (e.g. cp file /dir1/ /dir2/ /dir3/. Would that be possible? If yes, please provide the command for GNU/Linux or Unix operating systems. The short answer is no. You can not use GNU/cp or BSD/cp to copy a single file to multiple directories. However, you can use combination of cp and xargs/parallel and other commands to copy a single file to multiple directories in MacOS, Linux, FreeBSD, OpenBSD, NetBSD and Unix-like systems.

The cp command

The basic cp command syntax is as follows to copy multiple files to a single directory:cp file1 /dir1/ cp file1 file2 file3 /dir1/

Copy file to multiple directories in Unix or Linux

The trick is to use the xargs command or GNU parallel command.

Copying one file named foo.txt to multiple directories called /tmp/1/, /tmp/2/, and /tmp/3 using xargs

The xargs command construct argument list(s) and execute utility such as cp or mv. The syntax is:

How to use tee command to copy file to multiple folders

Say you want to copy /etc/resolv.conf to /tmp/1/ and /tmp/2/, you run the tee command as follows:tee /tmp/1/resolv.conf /tmp/2/resolv.conf < /etc/resolv.conf
tee /tmp/1/resolv.conf /tmp/2/resolv.conf < /etc/resolv.conf >/dev/null You need to specify full path like /tmp/1/resolv.conf, otherwise you get the following error:

tee: /tmp/1/: Is a directory

How to use find command to copy files to multiple dirs simultaneously

The syntax is as follows for the find command:find /dir1/ /dir2/ -maxdepth 0 -exec cp filename {} \; To copy /etc/hosts simultaneously to /tmp/{1,2}/ and $HOME/3/ folders under a Linux/Unix/MacOS/FreeBSD etc, enter:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Your support makes a big difference:

I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft, takes a lot of my time and hard work to produce. If everyone who reads nixCraft, who likes it, contributes to support it with donations: