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: ${!arr[@]} lists the indexes of a bash array, gaps and all

Bash
~/tips/tip-bash-array-indexes

hosts=(web db cache)

Loop over positions or keys of an array, also after removing elements.

When you need the position of each item in a loop, counting from 0 to the length goes wrong as soon as the array has a hole in it. Bash can give you the real indexes.

Put ! in front of the array name:

hosts=(web db cache)
unset 'hosts[1]'
echo "${!hosts[@]}"   # 0 2
echo "${#hosts[@]}"   # 2

After the unset there are two elements, at positions 0 and 2. A loop from 0 to 1 would hit the missing one and skip cache. Looping over the indexes is safe:

for i in "${!hosts[@]}"; do
  echo "$i: ${hosts[i]}"
done

For an associative array made with declare -A, the same syntax gives you the keys, which is how you walk through a lookup table.

The keys of an associative array come back in no particular order, so sort them if the order matters. If you want a gap-free array again, copy it into itself with hosts=("${hosts[@]}"). I like that better than keeping a separate counter. Also note the quotes around 'hosts[1]' in the unset: without them, a file called hosts1 in the current folder could turn the brackets into a glob.

Further reading: Bash manual: Arrays

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