# Functions and Arrays

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

Updated: November 10, 2026

## [Functions](https://www.ask-codey.com/courses/bash-in-depth/topics/bash-functions)

1. [Functions: Naming a Job](https://www.ask-codey.com/lessons/bash-functions) (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](https://www.ask-codey.com/lessons/bash-function-return-values) (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](https://www.ask-codey.com/lessons/bash-script-libraries) (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](https://www.ask-codey.com/courses/bash-in-depth/topics/bash-lists)

1. [Arrays](https://www.ask-codey.com/lessons/bash-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](https://www.ask-codey.com/lessons/bash-associative-arrays) (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](https://www.ask-codey.com/courses/bash-in-depth/topics/exercise-bash-the-playlist-shuffler)

1. [Exercise: The Playlist Shuffler](https://www.ask-codey.com/lessons/exercise-bash-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.

Source: https://www.ask-codey.com/courses/bash-in-depth/chapters/bash-functions-and-arrays
