I'm trying to copy a file from a folder into multiple folders using brace expansion like this:

cp source_folder/source.json target_folder{1..11}

But I get this error (for each target_folder name:

cp: target_folder1 is a directory (not copied).

What am I doing wrong?


The syntax of cp is something like

cp src1 src2 src3 ... srcn destdir

The means when target_folder{1..11} expands, the first 10 items will be treated as source names, and only the last as the directory. And as the first ones treated as source names are directories, you get the error message you quoted.

Or in other words: You can't use cp to copy to multiple directories in a single command, not with brace expansion, nor otherwise.

Use a loop instead (untested):

for d in target_folder{1..11} ; do cp source_folder/source.json "$d" ; done

What am I doing wrong?

Brace expansion generates multiple arguments. cp does not see what you type, it sees what the shell provides after it expands what you typed. cp does not support multiple targets, it supports multiple sources though. In your (expanded) command only the last argument is interpreted as a target. All but one arguments resulting from the brace expansion are considered to be additional sources.

target_folder1 is a directory (not copied) means target_folder1 is interpreted as a source but it was not copied because directories cannot be copied unless you use -R or equivalent option.

To copy to multiple destinations you can adapt the solution from this answer. In your case there is a single file to be copied, so it would be like:

<source_folder/source.json tee target_folder{1..11}/source.json >/dev/null

Note tee reads the source file just once. With cp the most obvious solution is to loop over destinations and call a separate cp process for each. This would read the file many times though. In your case it may not matter much, but if the file was large then you certainly wouldn't want to read it eleven times.

  • OTOH, cp is optimized for copying, while tee is not, so I am not actually sure which would be better under which circumstances... but I guess the files would have to be really large for it to matter enough to test this. – dirkt Nov 3 '19 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.