Reliable version-independent (3.2 .. 4.4) method for bash to process an empty array in "-u" mode

While the solution proposed in Bash to expand an empty array using `set -u` will work fine for me, it turns out that the processing of arrays has been changed in the recently released (2016/09/16) bash 4.4 (available, for example, in Debian).

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

Now empty array extensions do not give a warning

 $ set -u $ arr=() $ echo "${arr[@]}" $ # everything is fine 

The solution suggested in a related question fails with bash -4.4:

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

Has anyone received suggestions regarding a (more or less) version-independent solution without additional checks on the length of the array or bash version? I am still learning the latest bash changes myself

EDIT

As my initial question seems to be somewhat confusing, here is a clarification of what I'm trying 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 (launch Arch Linux protocol):

 $ 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 Stretch):

 $ 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 

Or am I seriously mistaken for using bash arrays?

+1
arrays bash
Sep 25 '16 at 14:09
source share
1 answer

The space in front of + is incorrect; do you mean

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

However, it’s much easier to use the += operator.

 arr2+=(foo) 
+5
Sep 25 '16 at 14:18
source share



All Articles