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: cd folder || exit stops a shell script that ends up in the wrong place

Shell
~/tips/tip-shell-cd-or-exit

cd /srv/app/releases || exit 1

Make a script quit when cd fails, before it runs commands in the wrong folder.

A failed cd only prints an error. The script then carries on in whatever folder it was in, and if the next line is a cleanup with rm, that is a very bad place to be.

Add an exit to every cd in a script:

cd /srv/app/releases || exit 1
rm -rf ./old-*

If the folder does not exist, is not mounted or has the wrong permissions, cd returns non-zero, the part after || runs and the script stops right there. The rm never sees the wrong directory.

ShellCheck flags a bare cd for this reason, and I think it is one of its most useful warnings.

set -e would also stop the script here, but set -e has enough exceptions that I like this explicit check on the lines where it really counts. If you want a clear message, use a group:

cd "$target" || { echo "cannot cd to $target" >&2; exit 1; }

Inside a function you may prefer return 1 over exit 1, so the caller decides what happens. And if you only need another folder for one command, a subshell like (cd dir && make) keeps the main script where it was.

Further reading: ShellCheck SC2164, Bash manual: Lists of Commands

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