How to initiate array element to 0 in bash?

后端 未结 3 498
有刺的猬
有刺的猬 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.

提交回复
热议问题