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

数组 – 当设置nounset时,如何“ – @ – expand(”${array [@]}

发布时间:2020-12-16 01:49:21 所属栏目:安全 来源:网络整理
导读:我有set -o nounset选项的bash脚本(我想要那个!). 现在,我想构造一个命令调用,但我事先并不知道参数的数量,所以我想使用一个数组(下面的例子).但是,当ARRAY为空数组时,“${ARRAY [@]}”失败. 问题:如何@ -expand数组(“${ARRAY [@]}”)以便在设置-o nounse
我有set -o nounset选项的bash脚本(我想要那个!).
现在,我想构造一个命令调用,但我事先并不知道参数的数量,所以我想使用一个数组(下面的例子).但是,当ARRAY为空数组时,“${ARRAY [@]}”失败.

问题:如何@ -expand数组(“${ARRAY [@]}”)以便在设置-o nounset时扩展不会失败?

例:

# Clone git repo. Use --reference if ${reference_local_repo} exist.
reference_local_repo=.....
test -d "${reference_local_repo}" 
    && reference=("--reference" "${reference_local_repo}") 
    || reference=()
git clone "${reference[@]}" http://address/of/the/repo

当然,我可以使用以下代码:

# bad example
reference=''
test -d "${reference_local_repo}" && reference="--reference ${reference_local_repo}"

…但如果本地存储库的路径包含空格,则无法工作.

作为一种解决方法,我使用reference =(“ – c”“dummy.dummy = dummy”)代替reference =().这样我就避免了空数组,而Bash也没有抱怨.或者,我可以(重命名数组变量和)将“clone”作为第一个数组元素.所以我得到了这个,但我想学习正确的方法.

为了记录,我使用的是GNU bash,版本4.3.42(1)-release(x86_64-pc-linux-gnu).

解决方法

回答你的具体问题:解决这个问题的一个非常古老而简单的方法是:

${reference[@]+"${reference[@]}"}

如果未设置引用,则不会扩展任何内容.
如果已设置,则会扩展其所有组件.

Read the historical roots for this use:

Once upon 20 or so years ago,some broken minor variants of the Bourne Shell substituted an empty string “” for “$@” if there were no arguments,

当然,在这个特定情况下:

test -d "${reference_local_repo}" && abool="" || unset abool
git clone ${abool+--reference "$reference_local_repo"} http://address/of/the/repo

当abool设置为NUL(“”)(或者如果您选择使用其他值时),它会被设置,并且在下一行中它会扩展到加号之后的内容(是的,正好是两个参数).

当abool未设置时,它会在下一行扩展中完全消失.

也许这更详细:

unset abool
if test -d "${reference_local_repo}"; then abool="ValidDir"; fi
git clone ${abool+--reference "$reference_local_repo"} http://address/of/the/repo

(编辑:李大同)

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

    推荐文章
      热点阅读