🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Arrays

An array is a variable that holds many values in order. Bash reads one value by its position number.

Read the first item

The code creates an array with three colors. It prints the value at index 0.

colors=(red green blue)
echo "${colors[0]}"

Read other items

Index 1 holds the second value. Index 2 holds the third value.

colors=(red green blue)
echo "${colors[1]}"
echo "${colors[2]}"

Read all items

The @ symbol stands for all items. It prints every value in order.

colors=(red green blue)
echo "${colors[@]}"

Example

colors=(red green blue)
echo "First is ${colors[0]}"
echo "Second is ${colors[1]}"
echo "All are ${colors[@]}"

Key points

  • Use parentheses to create an array like colors=(red green blue).
  • The first position in an array is index 0.
  • Write ${colors[0]} to read the value at index 0.
  • Write ${colors[@]} to read all values at once.
  • An array holds many values under one name.

In this example, the array colors holds three values. The first echo prints the value at index 0. The second echo prints the value at index 1. The last echo prints all values with ${colors[@]}.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ${colors[1]} print when colors=(red green blue)?