What does `shift` do, and how do you parse long options without `getopts`?
IntermediateConceptArrays, conditionals and loops
Answer
shift drops $1 and moves the rest down; shift 2 drops two. It returns non-zero (silently, unless shopt -s shift_verbose) if there are not enough arguments.
env="" dry_run=0
while (($#)); do
case $1 in
-e|--env) env=${2:?--env needs a value}; shift 2 ;;
--env=*) env=${1#*=}; shift ;;
-n|--dry-run) dry_run=1; shift ;;
--) shift; break ;;
-*) echo "unknown option: $1" >&2; exit 2 ;;
*) break ;;
esac
done
This hand-written loop is the usual way to support --long options, since Bash's getopts only handles short ones.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate