我想在bash中编写一个函数,将参数转发给cp命令.例如:输入
<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path"
Run Code Online (Sandbox Code Playgroud)
我希望它实际上做到:
cp "path/with whitespace/file1" "path/with whitespace/file2" "target path"
Run Code Online (Sandbox Code Playgroud)
但相反,现在我正在实现:
cp path/with whitespace/file1 path/with whitespace/file2 target path
Run Code Online (Sandbox Code Playgroud)
我尝试使用的方法是将所有参数存储在数组中,然后只需将cp命令与数组一起运行.像这样:
function func {
argumentsArray=( "$@" )
cp ${argumentsArray[@]}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,它没有像我之前提到的那样传输引号,因此副本失败了.
就像$@,你需要引用数组扩展.
func () {
argumentsArray=( "$@" )
cp "${argumentsArray[@]}"
}
Run Code Online (Sandbox Code Playgroud)
但是,阵列在这里没有用处; 你可以$@直接使用:
func () {
cp "$@"
}
Run Code Online (Sandbox Code Playgroud)