Functions and Arrays

Organize a script into named pieces, and keep lists of things.

Updated

Functions

  1. Functions: Naming a Job (Journeyman): A function keeps a few commands under one name, so a script says the job's name instead of repeating its lines: define it with name() { }, call it by its name like any command, and hand it arguments, which it reads as $1, $# and "$@".
  2. Local Variables and Getting a Value Back (Journeyman): local keeps a function's variables to itself, so it can't change the script's by accident; a function hands back a result by printing it with echo, which the caller catches with $( ), and answers yes or no with return, which if can test.
  3. One Script, Several Files: source (Journeyman): A library is a file of functions that several scripts share: each script loads it with source, and finds it from any folder with here=$(dirname "${BASH_SOURCE[0]}"), the folder the script itself is saved in.

Lists

  1. Arrays (Journeyman): An array keeps a list in numbered slots, counted from 0: songs=("Highway Tea" "Window Down") makes one, ${songs[0]} reads a slot, ${#songs[@]} counts the items, songs+=( ) adds one, "${songs[@]}" hands on every item in one piece, and mapfile -t fills an array from a file's lines.
  2. Associative Arrays: Lists with Names (Freelancer): An associative array finds each value by a name instead of a number: declare -A total makes one, total[chill]=15 stores a value under a name, "${!total[@]}" lists the names, and adding to total[$mood] inside a loop keeps a total for every category; it needs bash 4 or newer, which on a Mac means bash 5 from Homebrew.

Exercise: The Playlist Shuffler

  1. Exercise: The Playlist Shuffler (Journeyman): Finish the Playlist Shuffler, an application in two files: write the functions in its library that load the playlist into arrays, count it, add it up, answer whether a mood is there, pick a song at random and total each mood's minutes, then let a check script run it for real.