How to copy files to multiple locations on Linux

Using a series of commands to copy a file to multiple locations or a series of files to a single location can be time consuming, but there are options to speed up the process. This post explains some of them.

Several commands like this can copy a single file to a number of directories on your system:

$ cp myfile dir1
$ cp myfile dir2
$ cp myfile dir3

One way to simplify the task is to type the first command and then repeat the command, specifying only the necessary changes. This method relies on whether the file or directory names are similar enough to only replace part of the names.

# single file to multiple dirs        # multiple files to single dir
$ cp myfile dir1                      $ cp myfile1 dir
$ ^1^2^                               $ ^1^2^
cp myfile dir2                        cp myfile2 dir
$ ^2^3^                               $ ^2^3^
cp myfile dir3                        cp myfile3 dir

Another option is to use xargs Command to copy your file to multiple directories:

$ echo dir1 dir2 dir3 | xargs -n 1 cp -v myfile
'myfile' -> 'dir1/myfile'
'myfile' -> 'dir2/myfile'
'myfile' -> 'dir3/myfile'

In this case the xargs The command uses the information you provide (the directory names) to create each of the three commands required to copy the files to the three directories. That -v Argument ensures you see a list of copied files. That -n ensures that each command takes only one of the arguments provided by echo command in each of the commands that xargs runs. For comparison, when you run a command like this, you see three arguments per line:

$ echo Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec | xargs -n 3
Jan Feb Mar
Apr May Jun
Jul Aug Sep
Oct Nov Dec

A limitation of use xargs To run multiple commands, you must use the arguments that you send to the command echo is always appended to the end of the command being executed, so you can’t use the same technique to copy three files into a single directory. That see The command requires the last string to be the target directory and there is no way to get there xargs to reorder the commands. Obviously something like the following command won’t work.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply

Your email address will not be published. Required fields are marked *