10
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 array element to 0?

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The solution does not work for me, but this one works fine for me: declare -a job1Ids=( $(for i in $(seq 1 $cvFolds); do echo 0; done) )
@GoodWill Using variables instead of numbers to define the range limits is not supported (expanded) in bash, that's why your attempt probably failed. See unix.stackexchange.com/questions/7738/… The other possible problem is your bash version. This syntax was added in bash 3.0
2

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.

Comments

-1

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

1 Comment

"Does the declaration of array in this way in bash will initiate all the array elements to 0?" , Your answer : "Yes, it initiates an empty array". It Doesn't make sense. Then you show how to display the length of an array. You misread the question I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.