mkdir test_dir test_dir1 test_dir2 test_dir3
touch file1 file2 file3
cp -v file* test_dir*/

This copies only to test_dir3 and not in test_dir, test_dir1, test_dir2. Why?

For that matter it copies only to latest directory say test_dir4 and not into any other direcotry (it is omitting them).

  • Your last sentence is completely ununderstable. Please reformulate. – peterh - Reinstate Monica Mar 18 '15 at 9:29
  • @PeterH the OP is making an observation on the ordered expansion of the test_dir* wildcard. The final (target) directory on the command line is always the "last" directory in the ordered list. I think it's a confusion from * expansion being handled DOS style or Unix/Linux style. – roaima Mar 18 '15 at 9:49
  • @roaima Thank you - finally I deciphered it. But it wasn't trivial. :-) – peterh - Reinstate Monica Mar 18 '15 at 9:50

You have these three commands

mkdir test_dir test_dir1 test_dir2 test_dir3
touch file1 file2 file3
cp -v file* test_dir*/

Assuming no other files or directories in . before the example is started, the wildcards in that last line get expanded thus:

cp -v file1 file2 file3 test_dir/ test_dir1/ test_dir2/ test_dir3/

(You can see this by changing cp to echo cp and observing the result.) What you didn't tell us is the diagnostic messages produced by cp -v, which show what it is trying to do, i.e. copy every item on the command line but the last into the last item, which must therefore be a directory:

‘file1’ -> ‘test_dir3/file1’
‘file2’ -> ‘test_dir3/file2’
‘file3’ -> ‘test_dir3/file3’
cp: omitting directory ‘test_dir/’
cp: omitting directory ‘test_dir1/’
cp: omitting directory ‘test_dir2/’
| improve this answer | |

Because the cp commands works so. If it has more as 2 argument, the last argument must be a directory, and every argument before that will be copied into.

I think you want a cp which behaves much more like the windows copy command, and yes, there are such tools, although they aren't widely used. Even I had to google for that.

Your actual goal could be easily reached by a simple loop:

for i in test_dir*; do cp -v test_file* $i; done

It is much more simple as it seems on the first spot. Bash is actually a basic-like programming language, and doing loops or even more complex operations in single-line commands in a unix environment is quite common.

| improve this answer | |

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.