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: getopts parses the flags of a shell script without extra tools

Shell
~/tips/tip-shell-getopts-script-flags

while getopts 'f:v' opt; do

Reads short command line flags in a script with a built-in parser.

For small scripts a built-in option parser beats a hand-written loop of shifts.

while getopts 'f:v' opt; do
  case $opt in f) file=$OPTARG ;; v) verbose=1 ;; *) exit 2 ;; esac
done
shift $((OPTIND-1))

A letter followed by a colon takes an argument, which lands in $OPTARG. Letters without a colon are plain switches. After the loop, shift $((OPTIND-1)) leaves only the remaining arguments in $@. getopts handles short options only. For long ones like --file, you need a manual case loop.

Further reading: Bash manual: getopts

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