Created
April 9, 2021 05:07
-
-
Save z720/4854cdfac717dd5fbc51790a3900caff to your computer and use it in GitHub Desktop.
Bash command line parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # from https://medium.com/@Drew_Stokes/bash-argument-parsing-54f3b81a6a8f | |
| #!/bin/bash | |
| PARAMS="" | |
| while (( "$#" )); do | |
| case "$1" in | |
| -a|--my-boolean-flag) | |
| MY_FLAG=0 | |
| shift | |
| ;; | |
| -b|--my-flag-with-argument) | |
| if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then | |
| MY_FLAG_ARG=$2 | |
| shift 2 | |
| else | |
| echo "Error: Argument for $1 is missing" >&2 | |
| exit 1 | |
| fi | |
| ;; | |
| -*|--*=) # unsupported flags | |
| echo "Error: Unsupported flag $1" >&2 | |
| exit 1 | |
| ;; | |
| *) # preserve positional arguments | |
| PARAMS="$PARAMS $1" | |
| shift | |
| ;; | |
| esac | |
| done | |
| # set positional arguments in their proper place | |
| eval set -- "$PARAMS" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment