Linux bash-用引号括住所有数组元素或参数
我想在bash中编写一个函数,将参数转发给Linux bash-用引号括住所有数组元素或参数,linux,bash,Linux,Bash,我想在bash中编写一个函数,将参数转发给cp命令。 例如: 输入 <function> "path/with whitespace/file1" "path/with whitespace/file2" "target path" 但是,现在我正在实现: cp path/with whitespace/file1 path/with whitespace/file2 target path 我尝试使用的方法是将所有参数存储在一个数组中,然后与数组一起运行cp命令。 像这样: f
cp
命令。
例如:
输入
<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path"
但是,现在我正在实现:
cp path/with whitespace/file1 path/with whitespace/file2 target path
我尝试使用的方法是将所有参数存储在一个数组中,然后与数组一起运行cp命令。
像这样:
function func {
argumentsArray=( "$@" )
cp ${argumentsArray[@]}
}
不幸的是,它没有像我前面提到的那样传输引号,因此复制失败。就像
$@
一样,您需要引用数组扩展
func () {
argumentsArray=( "$@" )
cp "${argumentsArray[@]}"
}
但是,数组在这里没有任何用途;您可以直接使用$@
:
func () {
cp "$@"
}
也请看,谢谢!它在执行
func“file.txt”/tmp
时工作,但在尝试使用func“*.txt”/tmp
时显示错误。原因是可以理解的(“外壳膨胀”,等等),但是。。。有解决办法吗?不是一个好办法。我建议将func
写入,您可以将其称为func/tmp*.txt
,这样您就可以使用shift
从位置参数列表中删除/tmp
,并使用“$@”
访问其余参数(来自*.txt
)。
func () {
cp "$@"
}