How to initiate array element to 0 in bash?

后端 未结 3 482
有刺的猬
有刺的猬 2020-12-19 06:52
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:23

    Your example will declare/initialize an empty array.

    If you want to initialize array members, you do something like this:

    declare -a MY_ARRAY=(0 0 0 0) # this initializes an array with four members
    

    If you want to initialize an array with 100 members, you can do this:

    declare -a MY_ARRAY=( $(for i in {1..100}; do echo 0; done) )
    

    Keep in mind that arrays in bash are not fixed length (nor do indices have to be consecutive). Therefore you can't initialize all members of the array unless you know what the number should be.

    0 讨论(0)
  • 2020-12-19 07:30

    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.

    0 讨论(0)
  • 2020-12-19 07:40

    Yes, it initiates an empty array and assigns it to MY_ARRAY. You could verify with something like this:

    #!/bin/bash
    declare -a MY_ARRAY=()
    echo ${#MY_ARRAY} # this prints out the length of the array
    
    0 讨论(0)
提交回复
热议问题