tttppp tttppp - 1 year ago 82
Bash Question

How can I add a help method to a shell script?

How do I check if a

attribute has been passed into a shell script? I would like to display a help message when a user calls -h

Answer Source

here's an example for bash:

usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything

    -h  show this help text
    -s  set the seed value (default: 42)"

while getopts ':hs:' option; do
  case "$option" in
    h) echo "$usage"
    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
shift $((OPTIND - 1))