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: a shell exit code only goes up to 255, so exit 256 means success

Shell
~/tips/tip-shell-exit-code-range

bash -c 'exit -1'; echo $? # 255

Keep exit codes between 0 and 255, because larger numbers wrap around.

Using a count as the exit code, like exit $errors, seems clever until there are exactly 256 errors and the script reports success.

The exit status is stored in 8 bits, so only the value modulo 256 survives:

bash -c 'exit 256'; echo $?   # 0
bash -c 'exit 300'; echo $?   # 44
bash -c 'exit -1';  echo $?   # 255

Anything that checks for zero, like cron, systemd or if, sees the 256 case as a clean run. I’d cap the value instead:

(( errors > 0 )) && exit 1
exit 0

If you want to pass on how many things failed, print the number and keep the exit code simple.

Some numbers already mean something, so avoid them for your own errors. 126 means a command was found but could not run, 127 means it was not found, and 128 plus a number means the process died from that signal, so 130 is Ctrl-C and 143 is SIGTERM. Codes between 1 and 125 are safe to pick for your own reasons. Use a few, and write down in the script what each one means.

Further reading: Bash manual: Exit Status

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link