Whenever writing a script you might want to enable some options depending on what you provide on the CLI.
I’ve created a bash script template to getting started quick with a bash script. You can specify full options or the short ones with arguments or without.
#!/bin/bash
# Version 2.0
# Script template
set -eou pipefail
DO_OPT_A=false
DO_OPT_B=false
# directory of the script, can be useful for locating files which are next to the script.
THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
function main() {
check_root
do_parse_opts $@
[[ ${DO_OPT_A} = true ]] && check_opt_a_prerequisites
[[ ${DO_OPT_B} = true ]] && check_opt_b_prerequisites
print_info "Checks OK, you have 2s to abort now!"
sleep 2
echo ""
[[ ${DO_OPT_A} = true ]] && {
do_opt_a_function
}
[[ ${DO_OPT_B} = true ]] && {
do_opt_b_function
}
}
function show_help() {
echo "Scripting template :)"
echo "Usage:"
echo " $0 [-a/--option_a] [-b/--option_b <arg>]"
echo " * [-h/--help] Print this help"
echo " * [-a/--option_a] Perform option A"
echo " * [-b/--option_b <arg>] Perform option B with argument"
echo ""
exit 1
}
function do_parse_opts() {
# convert long options to shorts
for arg in "$@"; do
shift
case "$arg" in
"--help") set -- "$@" "-h" ;;
"--option_a") set -- "$@" "-a" ;;
"--option_b") set -- "$@" "-b" ;;
*) set -- "$@" "$arg"
esac
done
OPTIND=1 # Reset in case getopts has been used previously in the shell.
while getopts "hab:" opt; do
case "$opt" in
h)
show_help
exit 0
;;
a) DO_OPT_A=true
;;
b) DO_OPT_B=true
BARG=$OPTARG
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
print_info "DO_OPT_A = $DO_OPT_A"
print_info "DO_OPT_B = $DO_OPT_B"
[[ ${DO_OPT_A} = false ]] && [[ ${DO_OPT_B} = false ]] && {
print_info "Hey! Your provided no options, this might help:"
echo ""
show_help
}
echo ""
}
function check_root() {
[[ $EUID -ne 0 ]] && {
echo "[ERROR] This script must be run as root"
show_help
}
}
function check_opt_a_prerequisites() {
print_info "Checking option A prerequisites"
sleep 1
print_ok
}
function check_opt_b_prerequisites() {
print_info "Checking option B prerequisites"
sleep 1
print_ok
}
function do_opt_a_function() {
print_info "Performing A"
sleep 1
print_ok
}
function do_opt_b_function() {
print_info "Performing B, with arg: ${BARG}"
sleep 1
print_ok
}
function print_ok() {
echo "[OK]"
}
function print_info() {
echo "[INFO] $1..."
}
function print_error() {
echo "[ERROR] $1"
exit 1
}
main $@
print_info "All done!"
echo "[OK]"