Skip to content

Instantly share code, notes, and snippets.

@Taisho
Forked from Decstasy/args_parser.sh
Created January 16, 2024 18:42
Show Gist options
  • Save Taisho/ae6dd88ebcc11b9fca4d246a50bc4e76 to your computer and use it in GitHub Desktop.
Save Taisho/ae6dd88ebcc11b9fca4d246a50bc4e76 to your computer and use it in GitHub Desktop.
Parse Bash arguments without getopts or getopt
#!/bin/bash
# Dennis Ullrich
# Version 0.1-0 (2017-06-29)
# [email protected]
# Bash Version 3 required (it also works with ksh)
[[ ${BASH_VERSINFO[0]} -lt 3 ]] && exit 1
# Defaults
stdin=0
csv=0
param=""
# Put all arguments in a new array (because BASH_ARGV is read only)
ARGS=( "$@" )
for i in "${!ARGS[@]}"; do
case "${ARGS[i]}" in
'') # Skip if element is empty (happens when it's unsetted before)
continue
;;
-s|--stdin) stdin=1
;;
--csv) csv=1
;;
-p|--param) # Use +1 to access next array element and unset it
param="${ARGS[i+1]}"
unset 'ARGS[i+1]'
;;
--) # End of arguments
unset 'ARGS[i]'
break
;;
*) # Skip unset if our argument has not been matched
continue
;;
esac
unset 'ARGS[i]'
done
# In case you want to process more, there is nothing lost except the already parsed arguments with options.
# Keep in mind there was not a single shift!
echo "Unused Arguments:"
for i in "${!ARGS[@]}"; do
echo "$i: ${ARGS[i]}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment