brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: declare -A gives bash a lookup table with names as keys

Bash
~/tips/tip-bash-declare-associative-array

declare -A port=(

Stores values under names in a bash script, so you can look them up by key.

A lot of shell scripts fake a lookup table with a long case block or two arrays that have to stay in the same order. Bash has a real one: the associative array, where the keys are strings instead of numbers.

You create it with declare -A and fill it with [key]=value pairs:

declare -A port=(
  [jellyfin]=8096
  [sonarr]=8989
)
port[radarr]=7878

echo "${port[sonarr]}"     # 8989
echo "${#port[@]}"         # 3

The keys come out with ${!port[@]}, which makes a loop over everything easy. This is the kind of thing I’d want for a quick health check of the apps on a home server:

for app in "${!port[@]}"; do
  if curl -fsS -o /dev/null "http://192.168.1.10:${port[$app]}"; then
    echo "$app is up"
  else
    echo "$app does not answer"
  fi
done

To check whether a key exists, use [[ -v port[plex] ]], and unset 'port[sonarr]' removes one entry.

The caveat is the declare -A itself. Forget it, and bash quietly makes a normal indexed array. Its subscripts are arithmetic, so a word like jellyfin is read as a variable name, comes out as 0, and every “key” you set overwrites element 0. You get no error at all, just one value left. Associative arrays also need bash 4.0 or newer, and inside a function declare -A makes the array local unless you add -g.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link