加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – bash – 用引号括起所有数组元素或参数

发布时间:2020-12-14 00:35:41 所属栏目:Linux 来源:网络整理
导读:我想在bash中编写一个函数,将参数转发给cp命令. 例如: 输入 function "path/with whitespace/file1" "path/with whitespace/file2" "target path" 我希望它实际上做到: cp "path/with whitespace/file1" "path/with whitespace/file2" "target path" 但相
我想在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[@]}
}

不幸的是,它没有像我之前提到的那样传输引号,因此副本失败了.

解决方法

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

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

但是,阵列在这里没有用处;你可以直接使用$@:

func () {
    cp "$@"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读