Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cp copy command with bash brace expansion

at the bash prompt I can perform this copy

cp file.txt test1.txt

but if I try to copy file.txt to several files like so

cp file.txt test{2..4}.txt

I get error

cp: target `test4.txt' is not a directory

like image 584
Dr Blowhard Avatar asked Apr 07 '11 12:04

Dr Blowhard


2 Answers

It's not about bash, it's about cp. If you supply cp with more than two parameters the last one should be a directory to which all others are to be copied.

for f in test{2..4}.txt ; do cp file.txt $f ; done
like image 85
Michael Krelin - hacker Avatar answered Sep 17 '22 13:09

Michael Krelin - hacker


Well, you have to understand how *nix shells work.

In the DOS/Windows world, wildcards are handled by the programs. Thus, xcopy *.txt *.bak, for instance, means xcopy is given 2 parameters: *.txt and *.bak. How the wildcards are interpreted fully depends on xcopy.

In the *nix world, wildcards are handled by the shell. A similar command xcopy *.txt *.bak, for instance, gets expanded first becoming xcopy <list of files ending with .txt> <list of files ending with .back>. Thus assuming the existence of file1.txt to file4.txt, plus another file old.bak, the command will be expanded to xcopy file1.txt file2.txt file3.txt file4.txt old.bak

For the cp command, it's exactly what Michael has written: If you give cp more than 2 args, the last arg must be a directory.

like image 25
pepoluan Avatar answered Sep 17 '22 13:09

pepoluan