Bash: Data structures – code examples
Working with an Array
Use case: Store a list of files, hosts or options safely (even with spaces).
zahlen=(5 3 8 1)
zahlen+=(10)
echo "Count: ${#zahlen[@]}"
echo "First: ${zahlen[0]}, last: ${zahlen[@]: -1}"
echo "All: ${zahlen[@]}"
sortiert=$(printf '%s\n' "${zahlen[@]}" | sort -n | tr '\n' ' ')
echo "Sorted: $sortiert"Arrays are created in parentheses, += appends, ${#arr[@]} counts. ${arr[@]: -1} returns the last element (with Bash 4.3+ ${arr[-1]} also works). You delegate sorting to sort.
Associative Array
Use case: Store mappings such as country code to name or hostname to IP.
declare -A person=([name]="Ada" [alter]=36)
person[stadt]="London"
for schluessel in "${!person[@]}"; do
echo "$schluessel = ${person[$schluessel]}"
done
echo "E-Mail: ${person[email]:-no email}"declare -A creates a dictionary (Bash 4+, not in the macOS system Bash 3.2). ${!person[@]} returns the keys; the order is not guaranteed.
Object Substitute with Functions and a Namespace
Use case: Bundle related data and actions, e.g. for configuration or accounts in larger scripts.
# Bash has no classes: prefix namespace + associative array
declare -A konto
konto_init() { konto[besitzer]="$1"; konto[saldo]=0; }
konto_einzahlen() { konto[saldo]=$(( konto[saldo] + $1 )); }
konto_zeige() { echo "${konto[besitzer]}: ${konto[saldo]} EUR"; }
konto_init "Ada"
konto_einzahlen 100
konto_einzahlen 50
konto_zeigeBash has no classes or inheritance. The closest substitute: data in an associative array (Bash 4+) and functions with a common prefix. For serious object models, Bash is the wrong language.