Skip to content

Instantly share code, notes, and snippets.

@dir
Last active January 14, 2026 19:16
Show Gist options
  • Select an option

  • Save dir/be1db5e6347e1cc2fb38aa872f1b488f to your computer and use it in GitHub Desktop.

Select an option

Save dir/be1db5e6347e1cc2fb38aa872f1b488f to your computer and use it in GitHub Desktop.
Bash simple args/options/flags parsing snippet
#!/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 "$@"
@dir
Copy link
Copy Markdown
Author

dir commented Jan 9, 2026

This solution handles most common quick use cases, however, it does not handle:

  1. Variable validation (i.e. specific types)
  2. Empty variables
  3. Duplicate/repeated options (currently will use the value of the last passed option).
  4. Anything coming from stdin

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