How to copy a file to multiple folders using the command line?
Solution 1:
cp
can copy from multiple sources, but can't copy to multiple destinations. See man cp
for more info.
The only bash command that I know which can copy/save to multiple destinations is tee
.
You can use it in your case as follows:
tee ~/folder1/test.txt ~/folder2/test.txt < ~/test.txt
Note that tee
also writes the input to the standard output (stdout). So if you don't want this, you can prevent it by redirecting standard output to /dev/null
as follow:
tee ~/folder1/test.txt ~/folder2/test.txt < ~/test.txt >/dev/null
Solution 2:
Another way to achieve a copy to multiple locations is the following command :
find dir1 dir2 -exec cp file.txt {} \;
If dir1 or dir2 have sub-directories that you don't want the file copied into, add
-maxdepth 0
option :
find dir1 dir2 -maxdepth 0 -exec cp file.txt {} \;
Note that this will overwrite every file in dir1
and dir2
with file.txt
's contents, in addition to copying it. To only copy file.txt
without affecting other files in these directories, tell find
to only act on directories:
find dir1 dir2 -type d -exec cp file.txt {} \;
Solution 3:
The command
cp ~/test.txt ~/folder1 ~/folder2
tries to copy two files (~/test.txt
and ~/folder1
) to the destination folder2
. (And if ~/folder2
exists and is a directory you will have an "omitting directory" warning).
If you want to make multiple copies of the file test.txt
, you have to use a loop or multiple commands...
for i in ~/folder1 ~/folder2; do cp ~/test.txt $i; done
(...and be careful if you have spaces embedded in the file names, you'll need quoting).
To copy whole directories you have to use the -r
option:
for i in ~/folder1 ~/folder2; do cp -r ~/folder3 $i; done
this will create ~/folder1/folder3
and ~/folder2/folder3
with all the files included.