【问题标题】:bash - surround all array elements or arguments with quotesbash - 用引号包围所有数组元素或参数
【发布时间】:2016-03-08 13:27:20
【问题描述】:

我想在 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 path/with whitespace/file1 path/with whitespace/file2 target path

我尝试使用的方法是将所有参数存储在一个数组中,然后将 cp 命令与数组一起运行。 像这样:

function func {
    argumentsArray=( "$@" )
    cp ${argumentsArray[@]}
}

不幸的是,它并没有像我已经提到的那样转移引号,因此复制失败。

【问题讨论】:

标签: linux bash


【解决方案1】:

就像$@一样,你需要引用数组扩展。

func () {
    argumentsArray=( "$@" )
    cp "${argumentsArray[@]}"
}

但是,数组在这里没有用处;你可以直接使用$@

func () {
    cp "$@"
}

【讨论】:

  • 谢谢!它在执行func "the file.txt" /tmp 时有效,但在尝试使用func "*.txt" /tmp 时显示错误。原因明白了(“shell扩展”等),但是……有解决办法吗?
  • 不好。我建议将func 写给您可以将其称为func /tmp *.txt,以便您可以使用shift 从位置参数列表中删除/tmp,并使用"$@" 访问剩余的参数(来自@ 987654332@).
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2017-02-24
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
相关资源
最近更新 更多