Bash:在名称中包含空格且保存在变量中的目录之间复制文件

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

我正在使用 bash 将文件从一个目录复制到另一个目录。

这很好用:

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

但是当尝试将目录分配给脚本中的变量时它不起作用:

// 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

我找到了这个现有的答案,但我无法让它工作,而且答案没有添加太多细节,所以我真的不明白它是如何工作的: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"

如果只有一个源目录,请不要使用通配符。

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