How to initiate array element to 0 in bash?

后端 未结 3 1521
南旧
南旧 2020-12-19 07:00
declare -a MY_ARRAY=()

Does the declaration of array in this way in bash will initiate all the array elements to 0?

If not, How to initiate

3条回答
  •  爱一瞬间的悲伤
    2020-12-19 07:50

    Default Values with Associative Arrays

    Bash arrays are not fixed-length arrays, so you can't pre-initialize all elements. Indexed arrays are also not sparse, so you can't really use default values the way you're thinking.

    However, you can use associative arrays with an expansion for missing values. For example:

    declare -A foo
    echo "${foo[bar]:-baz}"
    

    This will return "baz" for any missing key. As an alternative, rather than just returning a default value, you can actually set one for missing keys. For example:

    echo "${foo[bar]:=baz}"
    

    This alternate invocation will not just return "baz," but it will also store the value into the array for later use. Depending on your needs, either method should work for the use case you defined.

提交回复
热议问题