Comment

Comment by databasher

Bash `getopts` handles short and long arguments gnu-style without any problem. The following code handles args like "-h", "-i $input-file", "-i$input-file", "--in=$input-file", and "--help":

  while getopts :i:h-: option
  do case $option in
         # accept -i $input-file, -i$input-file
         i ) input_file=$OPTARG;;
         h ) print_help;;
         - ) case $OPTARG in
                 help ) print_help;;
                 help=* ) echo "Option has unexpected argument: ${OPTARG%%=*}" >&2; exit 1;;
                 in=* ) input_file=${OPTARG##*=};;
                 in ) echo "Option missing argument: $OPTARG" >&2; exit 1;;
                 * ) echo "Bad option $OPTARG" >&2; exit 1;;
             esac;;
         '?' ) echo "Unknown option $OPTARG" >&2; exit 1;;
         : ) echo "Option missing argument: $OPTARG" >&2; exit 1;;
         * ) echo "Bad state in getopts" >&2; exit 1;;
     esac
  done
  shift $((OPTIND-1))
parent databasher 5 years ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton