Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiolimace/b124f47ca5f1f429ec3e8045b5aff653 to your computer and use it in GitHub Desktop.
Save fabiolimace/b124f47ca5f1f429ec3e8045b5aff653 to your computer and use it in GitHub Desktop.
The Universal Argument Parser using Bash's builtin getops
#!/bin/bash
# [MODIFICATION 1]
args=$@ # use builtin string substitution to simulate long options
args=${args//--long-option-a/-a} # replace `--long-option-a` with `-a`
args=${args//--long-option-b/-b} # replace `--long-option-b` with `-b`
args=${args//--long-option-c/-c} # replace `--long-option-c` with `-c`
# [MODIFICATION 2]
# replace unknown long options as
# they can cause parsing issues.
shopt -s extglob
args=${args//--+([a-zA-Z0-9-])/-?} # replace `--unknown-long-option` with '-?'
## arrays
declare -A options;
# [MODIFICATION 3]
# define the parameters
# using the silent mode
# set by the leading `:`
OPTSTRING=":a:b:c:d:e:f:"
# [MODIFICATION 4]
# use the modified `$args` instead of `$@`
while getopts "$OPTSTRING" name $args; do
# if argument parameter was given
if [[ ${OPTARG} ]]; then
options[${name}]=${OPTARG};
# if argument is just a flag
else
options[${name}]=${name};
fi
done;
## shift the $@
shift $(( ${OPTIND} - 1 ));
# [MODIFICATION 5]
# print arguments
printf ' $@: %s\n' "$args"
printf ' -a: %s\n' ${options['a']};
printf ' -b: %s\n' ${options['b']};
printf ' -c: %s\n' ${options['c']};
# The Universal Argument Parser
# Source: https://www.vivaolinux.com.br/artigo/getopts-criando-scripts-Bash-com-parametros-e-argumentos-personalizaveis
## arrays
declare -A options;
## collect arguments
while getopts "$OPTSTRING" name; do
# if argument parameter was given
if [[ ${OPTARG} ]]; then
options[${name}]=${OPTARG};
# if argument is just a flag
else
options[${name}]=${name};
fi
done;
## shift the $@
shift $(( ${OPTIND} - 1 ));
@fabiolimace
Copy link
Author

OUTPUT:

./the-universal-argument-parser-whith-long-options.sh --long-option-a 1 --long-option-b 2 --long-option-c 3 --unknown
 $@: -a 12 -b 2 -c 3 -?
 -a: 1
 -b: 2
 -c: 3

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