I'm trying to understand the point of ever explicitly declaring an array in bash. The course I'm doing states that you should create an array by using the command:
$ declare -a ARRAYNAME
I actually never knew about this command because I've never done my arrays like that. As an example, I wrote the script below and then deleted the 1st line of the file. The results were the same. Which begs the question, what's the actual point of ever using this "$ declare -a" statement since my course states that apparently this declare statement must be used (which I proved wrong)?
$ cat test6
declare -a car_models
car_models=( honda toyota bmw )
for i in "${!car_models[@]}"
do
echo " $i ${car_models[$i]}"
done
There is no reason I am aware of why you would have to declare it other than clarity and readibility of your code since declaring it is a clear indication to the next person who reads your code that "Hey, this variable will hold an indexed array".
On the other hand, declaring associative arrays is indeed useful. COnsider this example:
Running that gives:
As you can see, unlike with regular indexed arrays, if you don't declare the array as associative with
declare -A
it doesn't work.