Last active
April 29, 2021 08:40
-
-
Save nicordev/a6410e2fb11f065ce21329edcbd5f771 to your computer and use it in GitHub Desktop.
Bash arguments parsing snippet.
This file contains 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
#!/bin/bashPARAMS=""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" |
This file contains 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
#!/bin/bash | |
POSITIONAL=() | |
while [[ $# > 0 ]]; do | |
case "$1" in | |
-f|--flag) | |
echo flag: $1 | |
shift # shift once since flags have no values | |
;; | |
-s|--switch) | |
echo switch $1 with value: $2 | |
shift 2 # shift twice to bypass switch and its value | |
;; | |
*) # unknown flag/switch | |
POSITIONAL+=("$1") | |
shift | |
;; | |
esac | |
done | |
set -- "${POSITIONAL[@]}" # restore positional params |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From: