Skip to content

Instantly share code, notes, and snippets.

@Shardj
Last active April 29, 2022 10:17
Show Gist options
  • Save Shardj/3af8e7f899ac38de773e108941321378 to your computer and use it in GitHub Desktop.
Save Shardj/3af8e7f899ac38de773e108941321378 to your computer and use it in GitHub Desktop.
bash cli script bootstrap example, including coloured output, error handling, argument acception
#!/usr/bin/env bash
ColorOff='\033[0m' # Text Reset
Yellow='\033[0;33m' # Yellow for important info
Red='\033[0;31m' # Red for errors
function infoMessage() {
echo -e ${Yellow}
echo $1
echo -e ${ColorOff}
}
function errMessage() {
echo -e ${Red}
echo $1
echo -e ${ColorOff}
}
errHandler() {
# Any steps that must be taken prior to exiting due to error
errMessage "Something went wrong. Exiting now."
exit 1
}
set -eE # -e throw ERR for any non-zero exit codes, -E as well as in any child functions
trap 'errHandler' ERR INT # Call errHandler function on ERR (non-zero exit code) or INT (ctrl-c interupt execution)
# Usage info, literally just prints this text, to be called when -h is used
show_help() {
cat << EOF
Usage: [-hyd] [-j <job name>]
This command runs the app's... something
Parameter details:
-h display help and exit
-y skip the confirmation
-d dry run, don't push any changes
-j specify the name of the job
EOF
}
# Initialise variables
OPTIND=1 # Reset for previous uses of getops in shell
OPTSTRING="hydj:" # colon after character to tell getopts that we're expecting a value. No colon chars are just flags
# Location of this file
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR/.." # Go to project root, assuming your script is in a bin/ directory. You may need to adjust this line
while getopts "$OPTSTRING" opt; do
case "$opt" in
h)
show_help
exit 0
;;
y)
CONFIRMED=TRUE
;;
d)
DRY=TRUE
infoMessage "Running dry, wow this really stands out in yellow"
;;
j)
job="$OPTARG"
;;
*)
show_help >&2
exit 1
;;
esac
done
if [[ $OPTIND == 1 ]] && [[ $@ != "" ]]; then
echo "Arguments were passed that getopts didn't detect"
exit 1
fi
# Example of how to check for a flag, in this case it's -y aka $CONFIRMED
if [ -z "$CONFIRMED" ]; then
echo "-y flag was not set, $CONFIRMED is empty"
else
echo "-y flag was set, $CONFIRMED is not empty"
fi
if [ -n "$DRY" ]; then
echo "-d flag was set, $DRY is not empty"
else
echo "-d flag was not set, $DRY is empty"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment