Flags
Setting Flag Options
Setting flags with case
and shift
while test $# -gt 0; do
case "$1" in
|--help)
-hecho "$package - attempt to capture frames"
echo " "
echo "$package [options] application [arguments]"
echo " "
echo "options:"
echo "-h, --help show brief help"
echo "-a, --action=ACTION specify an action to use"
echo "-o, --output-dir=DIR specify a directory to store output in"
exit 0
;;
)
-ashift
if test $# -gt 0; then
export PROCESS=$1
else
echo "no process specified"
exit 1
fi
shift
;;
)
--action*export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'`
shift
;;
)
-oshift
if test $# -gt 0; then
export OUTPUT=$1
else
echo "no output dir specified"
exit 1
fi
shift
;;
)
--output-dir*export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'`
shift
;;
)
*break
;;
esac
done
Setting flags with getopts
a_flag=''
b_flag=''
files=''
verbose='false'
print_usage() {
printf "Usage: ..."
}
while getopts 'abf:v' flag; do
case "${flag}" in
) a_flag='true' ;;
a) b_flag='true' ;;
b) files="${OPTARG}" ;;
f) verbose='true' ;;
v) print_usage
*exit 1 ;;
esac
done
My personal use case…
while getopts "dl:svVyh" opt; do
case "$opt" in
) [[ -n "$DEBUG" ]] && unset DEBUG || DEBUG=true;;
d-n "$IS_REPO_LIST" ]] && unset IS_REPO_LIST || IS_REPO_LIST=true; REPO_LIST=${OPTARG};;
l) [[ -n "$IS_SILENT" ]] && unset IS_SILENT || IS_SILENT=true;;
s) [[ -n "$IS_VERBOSE" ]] && unset IS_VERBOSE || IS_VERBOSE=true;;
v) [[ -n "$IS_VERY_VERBOSE" ]] && unset IS_VERBOSE IS_VERY_VERBOSE || IS_VERBOSE=true; IS_VERY_VERBOSE=true;;
V) [[ ) [[ -n "$SKIP_CONFIRM" ]] && unset SKIP_CONFIRM || SKIP_CONFIRM=true;;
y
h) usage && exit 0;;-e "${SCRIPTPATH}:\n${RED}ERROR: Invalid flag.${NC}"
*) usage && echo
exit 1
esac
done 2>/dev/null"$((OPTIND-1))" shift
NOTE:
OPTARG
takes in optional argument if:
is presented after the flag option. e.ggetopts "l:"
will expect to take an optional flag argument like socommand -l "Optional argument"
. Also,getopts
does not support verbose flab options such as--help
.
WARNING:
OPTARG
at the end of a command may be considered a part of command line arguments even aftershift "$((OPTIND-1))"
.