Bash: How to Echo All Values in an Array


Often you may want to use the echo command in Bash to output all values in an array.

You can use the following basic syntax to do so:

echo "${my_array[*]}"

This particular example will output all values from the array named my_array.

By using the * as the array index in double quotes, Bash expands the array as a single word, which naturally displays all values in the array.

If you would like to display each value in the array on its own line, you can use the following syntax instead:

for x in ${my_array[@]}; do echo $x; done

This particular example will output all values from the array named my_array with each value on its own line.

The following example shows how to use this syntax in practice.

Example: How to Echo All Values in Array in Bash

Suppose that we create the following array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Hawks Nets Spurs Warriors Celtics Kings)

Now suppose that we would like to use the echo command to output all values from this array.

We can use the following syntax to do so: 

echo "${my_array[*]}"

The following screenshot shows how to use this syntax in practice:

Bash echo array

Notice that this outputs all values from the array named my_array.

Note that if you wanted to only display one particular value from the array then you could specify the index position to use instead of using the * character.

For example, you could use the following syntax to only output the first value from the array:

echo "${my_array[0]}"

The following screenshot shows how to use this syntax in practice:

Notice that this outputs only the first value from the array.

Note that you could also use the following syntax to display each value from the array on its own line:

for x in ${my_array[@]}; do echo $x; done

The following screenshot shows how to use this syntax in practice:

Bash echo each value from array on its own line

This outputs all values from the array with each value shown on its own line.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use Echo to Output a Multi-line String in Bash
How to Remove Spaces from String in Bash
How to Get Last Word of a String in Bash

Leave a Reply