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: += appends to a bash string or array in place

Bash
~/tips/tip-bash-plus-equals-append

s=foo; s+=bar; echo "$s" # foobar

Add to a string or array without repeating the variable name on the right.

Building a list of options in a script often turns into opts="$opts --exclude $x", which breaks as soon as a value has a space. Bash has an append operator that works with arrays.

On a string, += adds to the end. On an array, it adds new elements:

s=foo; s+=bar; echo "$s"       # foobar

opts=(-a --delete)
for dir in cache tmp "old stuff"; do
  opts+=(--exclude "$dir")
done
rsync "${opts[@]}" /srv/data/ /mnt/backup/

Each --exclude and each name is a separate element, so old stuff reaches rsync as one argument. With string building you would need fragile quoting tricks to get the same result.

The trap is in the parentheses. opts+=(x) appends an element, but opts+=x without them appends the text to the first element, which leaves you with something like -ax. Numbers are another: n=1; n+=1 gives 11, because it is still a string. Use (( n += 1 )), or declare the variable with declare -i if you want arithmetic. I’d keep to the array form for option lists, it saves plenty of quoting headaches.

Further reading: Bash manual: Shell Parameters, 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