Bash Best(ish) practices part 4
This is the final post in the series. I will follow up this post by commiting my code to github for easy access.
<code>#!/bin/bash
# bash template
# Print usage information and exit
print_usage(){
echo -e "\n" \
"usage: ./bashtemplate -o option \n" \
"\n" \
"-o <option> an option\n" \
"-h this help\n" \
"\n" && exit 1
}
###
# Options
###
# Loop through $@ to find flags
while getopts ":ho:" FLAG; do
case "${FLAG}" in
o) # Our option
OPTION="${OPTARG}" ;;
h) # Print usage information
HELP=1;;
[:?]) # Print usage information
print_usage;;
esac
done
###
# Functions
###
log_date(){
echo $(date +"%b %e %T")
}
error() {
NOW=$(log_date)
echo "${NOW}: ERROR: $1"
exit 1
}
warning() {
NOW=$(log_date)
echo "${NOW}: WARNING: $1"
}
info() {
NOW=$(log_date)
echo "${NOW}: INFO: $1"
}
# Do something
do_something(){
info "Doing something..."
warning "Encountered an anomaly while doing something."
}
###
# Program execution
###
[ "${HELP}" ] && print_usage
if [ ${OPTION} ]
then
info "Executing do_something()"
do_something
else
print_usage
fi
</code>
I have removed much of the extraneous stuff from the previous examples as I would like this to be generally useful for writing scripts.
The final element to cover is debugging. In bash the following options are available:
-e Stops execution if any external program returns non-zero.
-x Trace what is being executed.
-n Don’t execute. Useful for syntax errors.
These can also be turned on and off in the script with “set”.
Lets see them in action.
-x
<code>$ bash -x ./bashtemplate
+ getopts :ho: FLAG
+ '[' '' ']'
+ '[' ']'
+ print_usage
+ echo -e '\n' 'usage: ./bashtemplate -o option \n' '\n' '-o <option> an option\n' '-h this help\n' '\n'
usage: ./bashtemplate -o option
-o <option> an option
-h this help
+ exit 1
</code>
-n I introduced a syntax error.
<code>$ bash -n ./bashtemplate
./bashtemplate: line 70: syntax error near unexpected token `else'
./bashtemplate: line 70: `else'
</code>
-e I added a grep that would fail followed by an echo statement.
<code>$ bash -e ./bashtemplate
$
</code>
I hope this series has proven useful for someone other than myself, but if it has not I will never know.
https://github.com/jsutton/bashtemplate
Bash Best(ish) practices part 3 Bash Best(ish) practices part 2 Bash Best(ish) practices part 1