bash-用引号将所有数组元素或参数括起来 [英] bash - surround all array elements or arguments with quotes

查看:85
本文介绍了bash-用引号将所有数组元素或参数括起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用bash编写一个将参数转发到cp命令的函数. 例如: 输入

I want to write a function in bash that forwards arguments to cp command. For example: for the input

<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path"

我希望它实际执行:

cp "path/with whitespace/file1" "path/with whitespace/file2" "target path"

但是,相反,我现在正在实现:

But instead, right now I'm achieving:

cp path/with whitespace/file1 path/with whitespace/file2 target path

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

The method I tried to use is to store all the arguments in an array, and then just run the cp command together with the array. Like this:

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

不幸的是,它没有像我已经提到的那样传递引号,因此复制失败.

unfortunately, It doesn't transfer the quotes like I already mentioned, and therefore the copy fails.

推荐答案

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

Just like $@, you need to quote the array expansion.

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

但是,数组在这里没有任何作用.您可以直接使用$@:

However, the array serves no purpose here; you can use $@ directly:

func () {
    cp "$@"
}

这篇关于bash-用引号将所有数组元素或参数括起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆