Below is a short BASH scripting example how to use getopt and case together and provide better script command line argument handling than simple if-then-else. It accepts out of order arguments, multiple methods for the same argument (short and long), and ignores unrecognized arguments.
The script itself writes a ISO formatted date and time stamp to a file. The default options for the number of iterations (count), the interval between iterations (sleep) and the output file (write) can all be specified from the command line when running the script.
The script itself writes a ISO formatted date and time stamp to a file. The default options for the number of iterations (count), the interval between iterations (sleep) and the output file (write) can all be specified from the command line when running the script.
#!/bin/bash
usage () {
echo -e "Usage: tick.sh [-c #] [-s #] [ -w FILE ]"
echo -e "\t\t -c, --count= \t count for iterations to run (integer, default infinite)"
echo -e "\t\t -s, --sleep= \t sleep between iterations (integer, default 5)"
echo -e "\t\t -w, --write= \t write output to file (file system path, default ./tick-ISODATETIME.log)"
echo -e "\t\t -h, --help \t help"
}
debug () {
if [[ -z $boolQuiet ]] ; then
echo -e "intCount =\t$intCount"
echo -e "intSleep =\t$intSleep"
#echo -e "strTimeStamp =\t$strTimeStamp"
#echo -e "strLogFileName =\t$strLogFileName"
#echo -e "strLogFileDir =\t$strLogFileDir"
echo -e "strLogOutput = \t$strLogOutput"
if [[ -z intCount ]]; then
echo "Script tick.sh running INfinite iterations. Pressto cancel."
else
echo "Script tick.sh running finite iterations. Wait for prompt to return."
fi
fi
}
## NOTE: This requires GNU getopt; BASH built-in getopts is not equivalent
strGetOpt=`getopt --options c:s:w:qh --longoptions count:,sleep:,write:,quiet,help -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
## NOTE: quotes around $strGetOpt' are essential
eval set -- "$strGetOpt"
while [ $# -gt 0 ]; do
case "$1" in
-c | --count ) intCount="$2";;
-s | --sleep ) intSleep="$2";;
-w | --write ) strLogOutput="$2";;
-q | --quiet ) boolQuiet="1";;
-h | --help ) usage; exit 0;;
-- ) break;;
esac
shift
done
if [[ -z $strLogOutput ]]; then
strTimeStamp="$(date "+%Y%m%dT%T%:z")"
strLogFileName="tick-$strTimeStamp.log"
strLogFileDir="."
strLogOutput="$strLogFileDir/$strLogFileName"
fi
if [[ -z $intSleep ]]; then
intSleep="5"
fi
if [[ -z $intCount ]]; then
debug
while : ; do
echo "$(date "+%Y%m%dT%T:%N%:z")" >> "$strLogOutput"
sleep $intSleep
done
else
debug
i=$intCount
while [ $i -gt 0 ]; do
echo "$(date "+%Y%m%dT%T:%N%:z")" >> "$strLogOutput"
(( i-- ))
sleep $intSleep
done
fi
#echo -e "tick completed. Output written to:\t\"$strLogOutput\""
exit 0
#EOF
Comments