Print All Elements of Array to Console

To print all elements of an array in a single line to console output in Bash, we can use any of the following syntax.

  • echo ${arr[@]}
  • echo ${arr[*]}
  • echo ${arr[@]:0}
  • echo ${arr[*]:0}

Examples

In the following script, we take an array of elements, and print them to console in a single line using echo ${arr[@]}.

Example.sh

arr=("apple" "banana" "cherry")
echo ${arr[@]}

Output

apple banana cherry

Now, let us use the syntax echo ${arr[*]} to print all the elements of array to console in single line.

Example.sh

arr=("apple" "banana" "cherry")
echo ${arr[*]}

Output

apple banana cherry

Similarly, the other two variations mentioned above should print all the elements of given array to console in a single line.

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we have learnt how to print all the elements of an array to console output in a single line in Bash shell.