John Mellor
John Mellor

Reputation: 2503

Bash: Copy files between directories that have spaces in their names and which are held in a variable

I'm using bash to copy files from one directory to another.

This works fine:

mkdir "test dir"
mkdir "test dir 2"
touch "test dir/fileone"
touch "test dir/filetwo"
cp -r "test dir/"* "test dir 2/"

But when trying to assign the dirs to variables in a script it doesn't work:

// Setup
mkdir "test dir"
mkdir "test dir 2"
touch "test dir/fileone"
touch "test dir/filetwo"
from="test dir"
to="test dir 2"
cp -r "$from"* "$to"
// FAIL: cp: cannot copy a directory, 'test dir 2', into itself, 'test dir 2/test dir 2'
// This seems to be equivalent of cp -r ./* "$to"
cp -r "$from*" "$to"
// FAIL: cp: cannot stat 'test dir*': No such file or directory
// This is treating * as a string rather than a wildcard

I found this existing answer but I couldn't get it to work and the answers didn't add much detail so I didn't really understand how it was meant to work: filename contains space and wildcard in a variable

v=( ./test\ dir/ *)
echo "${v[@]}"
./test dir/ test dir test dir 2
// This seems to create an array of the string "test dir" and the contents of my current directory namely "test dir" and "test dir 2"

Upvotes: 0

Views: 2954

Answers (1)

Barmar
Barmar

Reputation: 781130

If there's just one source directory, don't use a wildcard.

from="test dir"
to="test dir 2"
cp -r "$from" "$to"

Upvotes: 1

Related Questions