Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

What is the difference between `getopts` and `getopt`?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer

getopts is a POSIX shell builtin: portable, short options only. getopt is an external program; the GNU version (util-linux) supports long options and reorders arguments, but the BSD/macOS version is broken with spaces in arguments.

opts=$(getopt -o e:v --long env:,verbose -n "$0" -- "$@") || exit 2
eval set -- "$opts"          # getopt quotes its output safely for eval
while true; do
  case $1 in
    -e|--env) env=$2; shift 2 ;;
    -v|--verbose) verbose=1; shift ;;
    --) shift; break ;;
  esac
done

For portability we use getopts or a hand-written while/case loop for long options.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells