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.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?IntermediateHow do you send a here-doc to a remote server over SSH, and when should variables expand locally vs remotely?Advanced