Last active
November 2, 2023 08:23
-
-
Save fabiolimace/b124f47ca5f1f429ec3e8045b5aff653 to your computer and use it in GitHub Desktop.
The Universal Argument Parser using Bash's builtin getops
This file contains 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
#!/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']}; |
This file contains 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
# 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 )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT: