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"
doneThis 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
MediumWrite a script that keeps a queue of names in an array and prints it numbered.
- Open
queue.sh. - Store all the script's arguments in an array named
queue, then addGuestto its end. - Print
First:followed by the first item, thenCount:followed by the number of items. - Loop over the queue and print each item as
N. NAME, numbering from 1. - 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. GuestThen run bash queue.sh with no names: the queue holds only the guest.
First: Guest
Count: 1
1. GuestTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV ReportPractice on your own: Terminal playground