Skip to content

Instantly share code, notes, and snippets.

@ajp619
Created January 26, 2025 16:28
Show Gist options
  • Save ajp619/5e477a1d1caadb807201e3089d5d983d to your computer and use it in GitHub Desktop.
Save ajp619/5e477a1d1caadb807201e3089d5d983d to your computer and use it in GitHub Desktop.
bash command line util template
#!/bin/bash
# create a place holder for positional args
POS_ARGS=""
while (( "$#" )); do #while there are still args to parse
# look at the first one
case "$1" in
# this is an example of a boolean flag.
-a|--my-boolean-flag)
# If present do something with MY_FLAG
MY_FLAG=0
# drop the first argument
shift
;;
# this is an example of a flag with an argument
-b|--my-flag-with-argument)
# check that there is an argument ($2) and that it does not start with '-'
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
# set MY_FLAG_ARG to $2
MY_FLAG_ARG=$2
# drop the first two arguments
shift 2
else
# output an error msg, (> &2 redirects to stderr)
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-*) # unsupported flags
# started with -*|--*=) but the second part seems unnecessary
# output an error msg, (> &2 redirects to stderr)
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
POS_ARGS="$POS_ARGS $1"
shift
;;
esac
done
# set positional arguments in their proper place -> $1 $2 ...
eval set -- "$POS_ARGS"
echo "my flag is $MY_FLAG"
echo "my flag arg=$MY_FLAG_ARG"
echo $POS_ARGS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment