Bash empty array expansion with `set -u`

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

    Here are a couple of ways to do something like this, one using sentinels and another using conditional appends:

    #!/bin/bash
    set -o nounset -o errexit -o pipefail
    countArgs () { echo "$#"; }
    
    arrA=( sentinel )
    arrB=( sentinel "{1..5}" "./*" "with spaces" )
    arrC=( sentinel '$PWD' )
    cmnd=( countArgs "${arrA[@]:1}" "${arrB[@]:1}" "${arrC[@]:1}" )
    echo "${cmnd[@]}"
    "${cmnd[@]}"
    
    arrA=( )
    arrB=( "{1..5}" "./*"  "with spaces" )
    arrC=( '$PWD' )
    cmnd=( countArgs )
    # Checks expansion of indices.
    [[ ! ${!arrA[@]} ]] || cmnd+=( "${arrA[@]}" )
    [[ ! ${!arrB[@]} ]] || cmnd+=( "${arrB[@]}" )
    [[ ! ${!arrC[@]} ]] || cmnd+=( "${arrC[@]}" )
    echo "${cmnd[@]}"
    "${cmnd[@]}"
    

提交回复
热议问题