Comment

Comment by databasher

Handling command-line arguments in Bash is easy. Bash's `getopts` handles short and long arguments gnu-style without any problem, out of the box, without any need for libraries or complicated packages.

This pattern handles lots of styles of options: short and long options (-h, --help), `--` for separating options from positional args, with GNU-style long options (--output-file=$filename).

  while getopts :o:h-: option
  do case $option in
         h ) print_help;;
         o ) output_file=$OPTARG;;
         - ) case $OPTARG in
                 help ) print_help;;
                 output-file=* ) output_file=${OPTARG##*=};;
                 * ) 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))
  (( $# > 0 )) && printf 'remaining arg: %s\n' "$@"
parent databasher 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton