Bash empty array expansion with `set -u`

后端 未结 11 2209
不知归路
不知归路 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:02

    @ikegami's answer is correct, but I consider the syntax ${arr[@]+"${arr[@]}"} dreadful. If you use long array variable names, it starts to looks spaghetti-ish quicker than usual.

    Try this instead:

    $ set -u
    
    $ count() { echo $# ; } ; count x y z
    3
    
    $ count() { echo $# ; } ; arr=() ; count "${arr[@]}"
    -bash: abc[@]: unbound variable
    
    $ count() { echo $# ; } ; arr=() ; count "${arr[@]:0}"
    0
    
    $ count() { echo $# ; } ; arr=(x y z) ; count "${arr[@]:0}"
    3
    

    It looks like the Bash array slice operator is very forgiving.

    So why did Bash make handling the edge case of arrays so difficult? Sigh. I cannot guarantee you version will allow such abuse of the array slice operator, but it works dandy for me.

    Caveat: I am using GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Your mileage may vary.

提交回复
热议问题