0

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?

1
  • If you add a Bash shebang, Shellcheck identifies the problems with the code snippets. See (the first paragraph of) the Stack Overflow 'bash' Info page for more about ShellCheck. Commented May 28, 2019 at 15:44

1 Answer 1

4

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.

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

Comments

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.