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: local keeps a bash function from overwriting your variables

Bash
~/tips/tip-bash-local-function-variables

count=10

Keeps the variables of a bash function inside that function, so callers keep their values.

This one surprises people who come from almost any other language: in bash, a variable you set inside a function is global by default. The function quietly changes the variable of whoever called it.

count=10
bump() { count=99; }
bump
echo "$count"    # 99

Put local in front and the variable only exists inside that function (and the functions it calls). When the function returns, the original value is back:

count=10
bump() { local count=99; }
bump
echo "$count"    # 10

In a short script it hardly matters, but once you have helper functions with names like file, i or dir, they will step on each other. My advice is to start every function by declaring its variables local, loop counters included. local takes the same options as declare, so local -a list and local -i n work too.

There is one trap. local is a command with its own exit status, and it returns 0 even when the command substitution inside it fails:

check() {
  local out=$(false)
  echo $?          # 0, the failure is gone
}

So with set -e or an if on $?, the error slips through. Split it into two lines, local out and then out=$(some_command), and the exit code of the command survives. ShellCheck flags this as SC2155 if you run it on your scripts.

Further reading: bash(1) manual page, ShellCheck SC2155

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