'-u'模式下bash空数组的可靠版本无关(3.2 .. 4.4)方式 [英] Reliable version-independent (3.2 .. 4.4) way of bash empty array handling in '-u' mode

查看:64
本文介绍了'-u'模式下bash空数组的可靠版本无关(3.2 .. 4.4)方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用`set -u`打击空数组扩展时,建议的解决方案对我来说非常有效,结果证明数组处理已在最近发布的(2016/09/16)bash 4.4中进行了更改(例如,在Debian Stretch中可用).

While the solution suggested in Bash empty array expansion with `set -u` worked great for me, turns out array handling has been changed in recently released (2016/09/16) bash 4.4 (available in Debian stretch, for example).

$ bash --version | head -n1
bash --version | head -n1
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)

现在,空数组扩展不会发出警告

Now empty arrays expansion does not emits warning

$ set -u
$ arr=()
$ echo "${arr[@]}"

$ # everything is fine

相关问题中提出的解决方案以bash-4.4失败:

The solution proposed in related question fails with bash-4.4:

$ set -u
$ arr2=()
$ arr2=( ${arr2[@] + "${arr2[@]}"} 'foo' )
bash: ${arr2[@] + "$arr2[@]"}: bad substitution

是否有人对(独立于版本的)解决方案提出了建议,而无需对数组长度或bash版本进行额外检查?我本人仍在调查最新的bash更改

Does anyone got suggestions on (more or less) version-independent solution without extra checks for array length or bash version ? I'm still on investigating latest bash changes myself

编辑

由于我最初的问题似乎有些令人困惑,因此请澄清我要达到的目标.测试脚本:

As my initial question seems to be somewhat confusing, here is clarification of what I try to achieve. Test script:

#!/usr/bin/env bash
set -euo pipefail
bash --version | head -n1

arr=()

# some external environment variables are set / command line arguments passed to script
if test -n "${USE_EXTRA_ARGUMENT_1-}" ; then
  arr=( ${arr[@] + "${arr[@]}"} 'foo' )
fi

if test -n "${USE_EXTRA_ARGUMENT_2-}" ; then
  arr=( ${arr[@] + "${arr[@]}"} 'bar' )
fi

# just a dummy command
echo "${arr[@]-}"

Bash 4.3(Arch linux)运行:

Bash 4.3 (Arch linux) run:

$ USE_EXTRA_ARGUMENT_1=baz bash xxx.sh 
GNU bash, version 4.3.46(1)-release (x86_64-unknown-linux-gnu)
foo

Bash 4.4(Debian拉伸)运行:

Bash 4.4 (Debian stretch) run:

$ USE_EXTRA_ARGUMENT_1=baz bash xxx.sh
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
xxx.sh: line 9: ${arr[@] + "${arr[@]}"}: bad substitution

还是我在使用bash数组时犯了严重错误?

Or I'm gravely wrong in using bash arrays ?

推荐答案

+ 之前的空格是错误的;你是说

The space before + is wrong; you mean

arr2=( ${arr2[@]+"${arr2[@]}"} 'foo' )

但是,使用 + = 运算符要简单得多.

It's much simpler, though, to use the += operator.

arr2+=(foo)

这篇关于'-u'模式下bash空数组的可靠版本无关(3.2 .. 4.4)方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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