Shell Script Template
I see the following requirements for shell scripts:
- Must not run only on Bash (thus use shebang
#!/bin/sh
)
- Must quit on errors and uninitialized variables (
set -ue
)
- Must print a usage when used wrong (e.g. wrong parameters)
- Must have a header, which explains the purpose of the script
#!/bin/sh -ue
#
# Script which reads variables from a .config file (key=value format)
#
# Author: Karl Krach
# Date: 2018/01/25
#
# Depends on: sh, cut, sed, tr
#
# Defaults
DUMMY_NUMBER=7
LOWERCASE="false"
KEEPNEWLINE="false"
print_usage() {
echo "USAGE: $(basename $0) [-l] [-d NUMBER] [--keep-newline] CONFIGFILE VARIABLE"
echo
echo "Reads variables from a .config file (key=value format)"
echo
echo " -h, --help shows this output"
echo " -d, --dummy dummy parameter (default: $DUMMY_NUMBER)"
echo " -l, --to-lowercase converts the output to lowercase (default: $LOWERCASE)"
echo " --keep-newline does not replace the linefeed by spaces (default: $KEEPNEWLINE)"
echo " CONFIGFILE the config file to read from"
echo " VARIABLE the variable to find"
echo
}
while [ $# -gt 0 ] ; do
case "$1" in
-h|--help)
print_usage
exit 0
;;
-d|--dummy)
shift
DUMMY_NUMBER="$1"
shift
;;
-l|--to-lowercase)
LOWERCASE="true"
shift
;;
--keep-newline)
KEEPNEWLINE="true"
shift
;;
--)
# end of flags, e.g. if parameter shall start with minus
shift
break
;;
-*)
echo "ERROR: Unknown parameter '$1'!"
echo
print_usage
exit 1
;;
*)
break
;;
esac
done
if [ $# -lt 2 ] ; then
echo "ERROR: Parameter missing!"
echo
print_usage
exit 1
fi
CONFIGFILE=$1
VARIABLE=$2
if [ ! -e "$CONFIGFILE" ] ; then
echo "ERROR: File '$CONFIGFILE' does not exist!"
echo
print_usage
exit 1
fi
grep "^$VARIABLE=" $CONFIGFILE | sed 's/^[^=]*=\(.*\)/\1/' | sed 's/^"\(.*\)"$/\1/' | \
( [ "$LOWERCASE" = "true" ] && tr '[:upper:]' '[:lower:]' || cat ) | \
( [ "$KEEPNEWLINE" = "true" ] && cat || tr -d '\n' )