How do I check if a -h
attribute has been passed into a shell script? I would like to display a help message when a user calls myscript.sh -h
.
here's an example for bash:
usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything
where:
-h show this help text
-s set the seed value (default: 42)"
seed=42
while getopts ':hs:' option; do
case "$option" in
h) echo "$usage"
exit
;;
s) seed=$OPTARG
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
To use this inside a function:
"$FUNCNAME"
instead of $(basename "$0")
local OPTIND OPTARG
before calling getopts
For example, a function that adds two numbers, or if the -s
option is given then subtract two numbers:
add () {
local OPTIND OPTARG opt operator="+"
while getopts :hs opt; do
case $opt in
s) operator="-" ;;
h) echo "a function to add or subtract two numbers";
return 1 ;;
\?) echo "unknown option: -$OPTARG" 1>&2;
return 2 ;;
esac
done
shift $((OPTIND - 1))
echo "$(( $1 $operator $2 ))"
}
$ add 15 4
19
$ add -s 15 4
11
$ add -h; echo $?
a function to add two numbers
1
$ add -x; echo $?
unknown option: -x
2