Bash empty array expansion with `set -u`

后端 未结 11 2233
不知归路
不知归路 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 15:51

    @ikegami's accepted answer is subtly wrong! The correct incantation is ${arr[@]+"${arr[@]}"}:

    $ countArgs () { echo "$#"; }
    $ arr=('')
    $ countArgs "${arr[@]:+${arr[@]}}"
    0   # WRONG
    $ countArgs ${arr[@]+"${arr[@]}"}
    1   # RIGHT
    $ arr=()
    $ countArgs ${arr[@]+"${arr[@]}"}
    0   # Let's make sure it still works for the other case...
    

提交回复
热议问题