#!/bin/bash
#:########################################################################
#: The option-string
#:
#: The option-string tells getopts which options to expect and which of them
#: must have an argument. The syntax is very simple . every option character
#: is simply named as is, this example-string would tell getopts to look
#: for -e, -d and -m:
#:
#: getopts fAx VARNAME
#:
#: When you want getopts to expect an argument for an option, just place
#: a : (colon) after the proper option flag. If you want -e to expect an
#: argument (i.e. to become -e ENVIRONMENT ) just do:
#:
#: getopts ed:m VARNAME
#:
#:########################################################################
function checkParam()
{
# if no paramter was supplied, show usage
text="Usage: $0 -e ENVIRONMENT -d DATE_FILENAME.TXT -m METRIC_FILENAME.TXT"
[ $# -eq 0 ] && { echo "$text"; exit 1; }
# parse the flags and options
while getopts "e:d:m:" opt; do
case $opt in
e)
echo "-$opt $OPTARG $OPTIND $OPTERR was triggered!" >&2
env=$OPTARG
;;
d)
echo "-$opt $OPTARG $OPTIND $OPTERR was triggered!" >&2
fdate=$OPTARG
;;
m)
echo "-$opt $OPTARG $OPTIND $OPTERR was triggered!" >&2
fmetric=$OPTARG
;;
*)
echo "Invalid option: -$opt $OPTARG $OPTIND $OPTERR" >&2
;;
esac
done
# show the flags and options that were parsed
echo "Environment: [$env]"
echo "Date filename: [$fdate]"
echo "Metric filename: [$fmetric]"
# Check the given files exist #
[ ! -f "$fdate" ] && { echo "Error: $fdate file not found."; exit 2; }
[ ! -f "$fmetric" ] && { echo "Error: $fmetric file not found."; exit 2; }
# Check the given files are not empty #
[ ! -s "$fdate" ] && { echo "Error: $fdate file is empty."; exit 2; }
[ ! -s "$fmetric" ] && { echo "Error: $fmetric file is empty."; exit 2; }
}
#: ## [ MAIN ] ###
checkParam $@
Friday, June 28, 2013
Bash Script using Flags and Options
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment