It's hard to test and edit bash scripts. It usually involves simultaneously writing, running, cleaning up errors generated by broken logic, and repeating. It would be nice to be able to do a "dry run" with the flip of a switch and see that every call is working as expected. This project introduces a single file with helper functions to help do this.
First, you source the file and define the DRY_RUN
and VERBOSE
booleans:
#/bin/bash
source "bash-cli-utils/cli.h"
VERBOSE=false
DRY_RUN=false
while getopts ":nv" opt; do
case "${opt}" in
n)
DRY_RUN=true
;;
v)
VERBOSE=true
;;
*)
echo "Unrecognized option -${OPTARG}"
exit 1
;;
esac
done
shift $((OPTIND-1))
# Here begins your command-line script logic
This introduces a few wrapper functions that you use throughout your script:
-
run
commandThis simply runs command. If the
DRY_RUN
switch is set, then the command simply gets echoed to standard output. -
debug
message_stringThis echoes the message_string only if the
VERBOSE
switch is set. -
create_empty
filenameThis creates an empty file at filename, or truncates it if it exists.
-
redirect
filename commandThis appends the standard output of command to the specified filename. If the
DRY_RUN
switch is set, then the command just gets echoed to standard output.
See the included example.sh
for an example of how this is used.