Signal9Signal9 — home
online
back to labs

Bash Arrays: Load, Index, and Join a List

MediumShell Scripting15-25 min
The brief

Arrays are how Bash holds a list you can index, count, and iterate — far better than re-splitting a string every time. Your per-session data is in /root/case/servers.txt (one hostname per line).

Write /root/scripts/summary.sh that loads the file into a Bash array and prints exactly these lines (order among them doesn't matter):

`

COUNT=<number of elements>

FIRST=<element at index 0, in file order>

LAST=<last element>

SORTED=<all elements sorted ascending, comma-joined, no spaces>

`

Use the array itself for every value: ${#arr[@]} for the count, ${arr[0]} and ${arr[-1]} for the ends, and a sorted copy joined with commas for SORTED. Grading runs your script and reads its output, then runs it again with a different servers.txt in place, so compute every value from the file rather than printing what you see in it.

What you'll do
  • Load a file into a Bash indexed array (mapfile -t)
  • Report the element count with ${#arr[@]}
  • Index the first and last elements (${arr[0]}, ${arr[-1]})
  • Sort a copy of the array and join it with commas

Hands-on lab: you work on a real Linux box in your browser, graded on the machine's actual state.