3 ms·
Recursive decent parsing! For example, here's a template for a script, with a `main` function, parsing for an `--interactive` flag, and handling of positional a
by da-x 3y ago
Recursive decent parsing! For example, here's a template for a script, with a `main` function, parsing for an `--interactive` flag, and handling of positional arguments. If you want an option to take an argument, you can simple extend the `case` with a new option, with shift and take `$1`.
#!/bin/bash
set -eu
set -o pipefail
set +o posix
main() {
local interactive=0
local positional=()
while [[ $# != 0 ]] ; do
if [[ "$1" =~ ^--(.*)$ ]] ; then
shift
local param
param="${BASH_REMATCH[1]}"
case ${param} in
interactive) interactive=1 ;;
*) "invalid parameter ${param}"; return 1 ;;
esac
else
positional+=("$1")
shift
fi
done
set -- "${positional[@]}"
if [[ "${interactive}" == "1" ]] ; then
echo "I am interactive"
else
echo "I am not interactive"
fi
echo "Rest of my arguments: "$@
}
main "$@"