user12353354
user12353354

Reputation:

Why is my array not behaving as expected?

#!/bin/bash

declare -a months
months=([11]=D [7]=A [0]=J F M A M J J S O N)

echo There are ${#months[@]} months in a year. They are:
echo ${months[@]}

I am learning Bash. I was experimenting with arrays (after having read about them in the Bash manual), and I wanted to experiment with the out-of-order assignment.

When I run my code, 'There are 11 months in a year' is outputted, followed by 'J F M A M J J S O N D'.

The eight element - 'A' seems to be not getting stored in the array, and it is not being outputted.

Why might this be?

Upvotes: 0

Views: 31

Answers (1)

choroba
choroba

Reputation: 242343

months=([11]=D [7]=A [0]=J F M A M J J S O N)

This assings D to index 11, A to index 7, J to index 0, F to index 1, M to index 2, A to index 3, M to index 4, J to indices 5 and 6, S to index 7 - overwriting the previously stored A!

If you want to store the whole string as a single element, quote it.

months=([11]=D [7]=A [0]='J F M A M J J S O N')

If you want the eighth element to be changed from A to S, put the [7]=A after the assignement to [0]=J F M....

Upvotes: 2

Related Questions