Argument parsing using a for loop
suggest changeA simple example which provides the options:
Opt | Alt. Opt | Details — | — | — -h
| --help
| Show help -v
| --version
| Show version info -dr path
| --doc-root path
| An option which takes a secondary parameter (a path) -i
| --install
| A boolean option (true/false) -*
| – | Invalid option
#!/bin/bash
dr=''
install=false
skip=false
for op in "$@";do
if $skip;then skip=false;continue;fi
case "$op" in
-v|--version)
echo "$ver_info"
shift
exit 0
;;
-h|--help)
echo "$help"
shift
exit 0
;;
-dr|--doc-root)
shift
if [[ "$1" != "" ]]; then
dr="${1/%\//}"
shift
skip=true
else
echo "E: Arg missing for -dr option"
exit 1
fi
;;
-i|--install)
install=true
shift
;;
-*)
echo "E: Invalid option: $1"
shift
exit 1
;;
esac
done
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents