Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

linux - How to initiate array element to 0 in bash?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...