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
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.
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.
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