I want to copy multiple files from one directory to another. I have a variable (files) that contains the following structure:

file1 file2

File1 and file2 are in dir1 and I want to copy them to dir2 with the following piece of code that doesn't seem to work:

cp ./dir1/$files ./dir2

1 Answer 1


There are several approaches. The simplest is to change into the first directory

cd dir1 ; cp $files ../dir2

One problem is that a string with names separated by spaces is not the best form for manipulating the names, in particular if they contain spaces. What you have is what you have, but let us hope you have bash, zsh, ksh or something like it which has arrays. Change the string into an array:

names=( $files )

Then you can apply transformations such as prepending "dir1/" onto each element of the names array.

cp "${names[@]/#/dir1/}" dir2

This is not the most obvious syntax, so let me break it down a bit.

  1. The first / introduces a substitution operation.
  2. The # matches the start of the element, similar to ^ in regular expressions.
  3. The second / ends the "from" part of the substitution.
  4. The dir1/ is the "to" part of the substitution, there is nothing special about the third / it is just a character in the "to" part.
  5. The [@] makes it apply to all elements in the array. The use of [@] inside double quotes stops word splitting.
  6. The { and } are needed to group the [@] and the substitution operation together with the variable name.
  7. The $ is just the normal variable reference.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .