2
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).

peterh
  • 4,953
  • 13
  • 30
  • 44
kumar
  • 433
  • 3
  • 10
  • 23
  • Your last sentence is completely ununderstable. Please reformulate. – peterh Mar 18 '15 at 09: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 09:49
  • @roaima Thank you - finally I deciphered it. But it wasn't trivial. :-) – peterh Mar 18 '15 at 09:50

2 Answers2

4

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/’
roaima
  • 1,591
  • 14
  • 28
2

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.

peterh
  • 4,953
  • 13
  • 30
  • 44