Skip to content

Instantly share code, notes, and snippets.

@nicordev
Last active April 29, 2021 08:40
Show Gist options
  • Save nicordev/a6410e2fb11f065ce21329edcbd5f771 to your computer and use it in GitHub Desktop.
Save nicordev/a6410e2fb11f065ce21329edcbd5f771 to your computer and use it in GitHub Desktop.
Bash arguments parsing snippet.
#!/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"
#!/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
@nicordev
Copy link
Author

nicordev commented Aug 7, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment