Bash empty array expansion with `set -u`

后端 未结 11 2204
不知归路
不知归路 2020-12-12 15:37

I\'m writing a bash script which has set -u, and I have a problem with empty array expansion: bash appears to treat an empty array as an unset variable during e

11条回答
  •  时光取名叫无心
    2020-12-12 16:13

    According to the documentation,

    An array variable is considered set if a subscript has been assigned a value. The null string is a valid value.

    No subscript has been assigned a value, so the array isn't set.

    But while the documentation suggests an error is appropriate here, this is no longer the case since 4.4.

    $ bash --version | head -n 1
    GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
    
    $ set -u
    
    $ arr=()
    
    $ echo "foo: '${arr[@]}'"
    foo: ''
    

    There is a conditional you can use inline to achieve what you want in older versions: Use ${arr[@]+"${arr[@]}"} instead of "${arr[@]}".

    $ function args { perl -E'say 0+@ARGV; say "$_: $ARGV[$_]" for 0..$#ARGV' -- "$@" ; }
    
    $ set -u
    
    $ arr=()
    
    $ args "${arr[@]}"
    -bash: arr[@]: unbound variable
    
    $ args ${arr[@]+"${arr[@]}"}
    0
    
    $ arr=("")
    
    $ args ${arr[@]+"${arr[@]}"}
    1
    0: 
    
    $ arr=(a b c)
    
    $ args ${arr[@]+"${arr[@]}"}
    3
    0: a
    1: b
    2: c
    

    Tested with bash 4.2.25 and 4.3.11.

提交回复
热议问题