Skip to content

Instantly share code, notes, and snippets.

@iamkirkbater
Last active May 7, 2020 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamkirkbater/c0a59f0f2c8fe1682428d7f4daba09de to your computer and use it in GitHub Desktop.
Save iamkirkbater/c0a59f0f2c8fe1682428d7f4daba09de to your computer and use it in GitHub Desktop.
A quick options set and verbosity output scaffold for new bash scripts
#!/bin/bash
usage() {
cat <<EOF
usage: $0 [ OPTIONS ]
Options
-d --dry-run Do not make any modifications but preview the expected operations
-h --help Show this message and exit
-q --quiet Be Quiet
-v --verbose Be Loud
EOF
}
# Remove this if check if there is not a need for parameters to be passed in.
if [ $# -lt 2 ]; then
usage
exit 1
fi
BE_QUIET=false
BE_VERBOSE=false
while [ "$1" != "" ]; do
case $1 in
-d | --dry-run ) DRY_RUN=true
;;
-h | --help ) usage
exit 1
;;
-q | --quiet ) BE_QUIET=true
;;
-v | --verbose ) BE_VERBOSE=true
;;
* ) echo "Unexpected parameter $1"
usage
exit 1
esac
shift
done
# Say is used as a wrapper to wrap things we don't want to be said if we're running in quiet mode
say() {
if [ "$BE_QUIET" == false ]; then
echo $@
fi
}
# sayv is used as a wrapper to wrap things we don't want to be said during quiet mode but be said durinv verbose mode.
# if both quiet and verbose flags are present quiet is respected.
sayv() {
if [ "$BE_QUIET" == false ]; then
if [ "$BE_VERBOSE" == true ]; then
echo $@
fi
fi
}
# dry_run will take a command you don't want to run and say it when the dry run flag is set but will actually run it if the dry run is not set.
dry_run() {
if [ -n "$DRY_RUN" ]; then
say "Dry Run, running \"$@\""
else
cmd=`eval "$@"`
sayv "$cmd"
fi
}
## Rest of script goes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment