shBash
AdvancedLesson 11 of 15

Arrays, Associative Arrays & Parameter Expansion – Bash

Handle lists safely and split strings without external programs.

Indexed arrays store word lists safely, even with spaces in the elements – unlike a string with spaces. Always expand with "${arr[@]}". Associative arrays (declare -A, key → value) exist from Bash 4; on macOS with the system Bash 3.2 they are missing.

dateien=("Bericht 1.txt" "notiz.txt" "Foto.png")
dateien+=("neu.md")                    # append
echo "Count: ${#dateien[@]}"           # 4
echo "First: ${dateien[0]}"            # Bericht 1.txt
echo "Ab Index 1: ${dateien[@]:1}"
for d in "${dateien[@]}"; do echo "- $d"; done

# associative array (Bash 4+)
declare -A hauptstadt=([DE]=Berlin [FR]=Paris)
hauptstadt[AT]=Wien
for land in "${!hauptstadt[@]}"; do echo "$land -> ${hauptstadt[$land]}"; done

Parameter expansion slices strings directly in the shell: #/## removes the shortest/longest match at the beginning, %/%% at the end; / replaces; ${#var} returns the length.

pfad="/home/ada/projekt/bericht.tar.gz"
echo "${pfad##*/}"        # bericht.tar.gz   (file name: remove the longest */ from the front)
echo "${pfad%/*}"         # /home/ada/projekt (folder: remove the shortest /* from the back)
echo "${pfad%.gz}"        # ...bericht.tar   (remove one suffix)
echo "${pfad%%.*}"        # /home/ada/projekt/bericht   (remove the longest .*)
name="bash-kurs"
echo "${name/-/_}  ${name//a/A}  ${#name}"   # bash_kurs  bAsh-kurs  9
echo "${name^^}  ${name^}  ${name,,}"        # Bash 4+: BASH-KURS  Bash-kurs  bash-kurs

In addition there are: ${var:-x} (default if empty), ${var:=x} (default and assign), ${var:?message} (abort if empty), ${var:+x} (x only if set) and substrings ${var:2:3}.

text="Happy Days"
echo "${text:0:5}"       # Happy
echo "${text: -4}"       # Days   (space before the minus!)
echo "${opt:+--verbose}" # empty if opt is not set

# read a file into an array (Bash 4+)
mapfile -t zeilen < server.log
echo "Lines: ${#zeilen[@]}"
Warningarr=$(ls) does not create a list but a string. Use arr=(*) or mapfile. And "${arr[*]}" glues elements together, "${arr[@]}" keeps them separate – the counterpart of "$*" vs. "$@". On macOS Bash 3.2, mapfile, declare -A and ${var^^} are also missing.
TipFor "real" data structures (nested, many values) Bash is the wrong choice – from there on, prefer Python. For JSON, the tool jq helps.