Last active
January 14, 2026 19:16
-
-
Save dir/be1db5e6347e1cc2fb38aa872f1b488f to your computer and use it in GitHub Desktop.
Bash simple args/options/flags parsing snippet
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
| #!/usr/bin/env bash | |
| parse_args() { | |
| local foo | |
| local bar=false | |
| local positional_args=() # < this line can technically be omitted, if you want to go very minimal | |
| while [[ $# -gt 0 ]]; do | |
| case "$1" in | |
| # CLI Options | |
| --foo=*) foo="${1#*=}" && shift ;; # Key/value option | |
| -f | --foo) foo="$2" && shift 2 ;; | |
| --bar) bar=true && shift ;; # Flag | |
| # Boilerplate handlers | |
| --) shift && break ;; # Common convention to signal end of opts | |
| -*) echo "Unknown option: $1" && exit 1 ;; # Error on unknown opt (remove to allow) | |
| *) positional_args+=("$1") && shift ;; # Collect positional args | |
| esac | |
| done | |
| set -- "${positional_args[@]}" "$@" && unset positional_args # Restore positional args to $@ | |
| echo -e "--- options ---" | |
| echo -e "-f, --foo:" "$foo" | |
| echo -e "--bar:" "$bar" | |
| echo -e "\n--- positional ---" | |
| echo -e "$@" "\n" | |
| } | |
| parse_args "$@" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution handles most common quick use cases, however, it does not handle: