How to initiate an array element to 0 in bash?

declare -a MY_ARRAY=() 

Will declaring an array this way in bash trigger all array elements to 0?

If not, then how to initiate an array element to 0?

+6
source share
3 answers

In your example, an empty array will be declared / initialized.

If you want to initialize the elements of an array, you are doing 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 (and indexes should not be consecutive). Therefore, you cannot initialize all members of the array if you do not know what the number is.

+14
source

Default Values ​​with Associative Arrays

Bash arrays are not fixed-length arrays, so you cannot pre-initialize all elements. Indexed arrays are also not allowed, so you cannot use the default values ​​as you think.

However, you can use associative arrays with an extension for missing values. For instance:

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

This will return a baz for any missing key. Alternatively, instead of just returning the default value, you can actually set one of them to have no keys. For instance:

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

This alternate call will not only return "baz", but will also store the value in an array for later use. Depending on your needs, any method should work for the case you are using.

+2
source

Yes, it initiates an empty array and assigns it MY_ARRAY . You can check something like this:

 #!/bin/bash declare -a MY_ARRAY=() echo ${#MY_ARRAY} # this prints out the length of the array 
-1
source

Source: https://habr.com/ru/post/944725/


All Articles