Recursively copy contents of directory to all target directories

2.1k views Asked by At

I have a directory containing a set of subdirectories and files. I need to recursively copy all the content of this directory to all the subdirectories of another directory, also recursively.

How do I achieve this, preferably without using a script and only with the cp command?

3

There are 3 answers

0
gdrooid On BEST ANSWER

You can write this in a script but you don't have to. Just write it line by line in the terminal:

# $TARGET is the directory containing subdirectories where you want to STORE the copies
# $SOURCE is the directory containing the subdirectories you want to COPY

for dir in $(ls $TARGET); do
   cp -r $SOURCE/* $TARGET/$dir
done

Only uses cp and runs on both bash and zsh.

0
Arnab Nandy On

The first part of the command before the pipe instruct tar to create an archive of everything in the current directory and write it to standard output (the – in place of a file-name frequently indicates stdout).

tar cf - * | ( cd /target; tar xfp -)

The commands within parentheses cause the shell to change directory to the target directory and untar data from standard input. Since the cd and tar commands are contained within parentheses, their actions are performed together.

The -p option in the tar extraction command directs tar to preserve permission and ownership information, if possible given the user executing the command. If you are running the command as superuser, this option is turned on by default and can be omitted.

Also you can use the following command, but it seems to be quite slower than tar;

cp -a * /target
0
jherran On

You can't. cp can copy multiple sources but will only copy to a single destination. You need to arrange to invoke cp multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.