Menu
CoddyTech

Arrays

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 19 of 39.

An array is one variable that holds a list of values. Create it with parentheses, with spaces between the items. Each item has an index, starting at 0.

fruits=(apple pear "green fig")
echo "${fruits[0]}"     # apple
echo "${fruits[2]}"     # green fig
echo "${#fruits[@]}"    # 3
fruits+=(plum)
echo "${fruits[@]}"     # apple pear green fig plum

${fruits[@]} is every item and ${#fruits[@]} is how many there are. +=(...) adds items to the end. Loop over the items with "${fruits[@]}" in double quotes, so an item with a space stays one item:

for f in "${fruits[@]}"; do
  echo "Buy: $f"
done

This prints four lines, one of them Buy: green fig. Without the quotes, green and fig print as two items. list=("$@") copies all of a script's arguments into an array.

challenge icon

Challenge

Medium

Write a script that keeps a queue of names in an array and prints it numbered.

  1. Open queue.sh.
  2. Store all the script's arguments in an array named queue, then add Guest to its end.
  3. Print First: followed by the first item, then Count: followed by the number of items.
  4. Loop over the queue and print each item as N. NAME, numbering from 1.
  5. Save the file.

Try it: run bash queue.sh Mia Tom "Ann Lee". It prints:

First: Mia
Count: 4
1. Mia
2. Tom
3. Ann Lee
4. Guest

Then run bash queue.sh with no names: the queue holds only the guest.

First: Guest
Count: 1
1. Guest

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground