user7288808
user7288808

Reputation: 137

Creating Bash Array with Multiple Elements

Very simple bash problem. I have an array that look like:

my_array=(1 2 3)

However, when I print the array or loop through it, bash only refers to the first element.

echo $my_array
1

for element in my_array ; do
    echo $element
done
1

How can I access all the elements?

Upvotes: 0

Views: 694

Answers (1)

choroba
choroba

Reputation: 241768

You need to use the proper syntax. To display all the elements, use

for element in "${my_array[@]}" ; do
    printf '%s\n' "$element"
done

$my_array is the same as ${my_array[0]}.

Also, the loop in the original question outputs my_array, not 1. Without a $, it's not a variable, it's just a word.

Upvotes: 4

Related Questions