I read How can I copy a file and create the target directories at the same time?But the solution there only works if you want to copy one file.How would I copy multiple files into a directory, that doesn't exist yet and auto-create it with one command?for example:cd /tmp/mkdir a/cd a/touch x1 x2cp --magic * ../b/c/d/so in the end the two files x1 and x2 are ordered like this:/tmp/b/c/d/x1/tmp/b/c/d/x2
Copy multiple files and create the target directories at the same time?
bash;cp
Use:$ copy() { mkdir -p -- ${@: -1} && cp -- $@ ; }$ copy * ../b/c/d/Note: it works with bash, ksh93 and zsh.${@: -1} corresponds to the ${parameter:offset} form: all parameters starting at the offset. The offset -1 corresponds to the last parameter, since negative offsets count from the end. The space is necessary, otherwise it would be the ${parameter:-word} form. See the bash manual for more information.$@ expands to the list of parameters, which is what is wanted for cp.Note 2: As suggested by mikeserv, you can useeval 'mkdir -p -- ${'$#'}'which is more portable (POSIX), instead ofmkdir -p -- ${@: -1}Concerning the performance, the eval solution is much faster with bash 4.3.30, but the other solution is faster with ksh 93u+ and zsh 5.0.6 (ksh93 and zsh being much faster than bash in both cases); and dash 5.7 with the eval solution (the other one is not supported) is a bit faster than ksh93 with the ${@: -1} solution. So, depending on your case (script, interactive use, support for specific shell features, etc.), make your choice... Note however that in the context of cp (which will take most of the time), these performance differences won't be noticeable.The script I used for the test:i=50000while [ $i -ne 0 ];do  # : ${@: -1}  eval ': ${'$#'}'  i=$((i-1))done(comment out the eval line and uncomment the previous line for the other solution), called with:time sh ./tst `seq 1000`time bash ./tst `seq 1000`time ksh93 ./tst `seq 1000`time zsh ./tst `seq 1000`