Created
February 11, 2019 15:19
-
-
Save lmcarreiro/aa8c09cadee1f488ff8ec9db434cf534 to your computer and use it in GitHub Desktop.
Bash script to get named arguments
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 | |
# File: test-args.sh | |
# | |
# Test with: | |
# ./test-args.sh --a1 a1 --a2 "a 2" --a3 --a4= --a5=a5 --a6="a 6" | |
# | |
# Output: | |
# a1 = "a1" | |
# a2 = "a 2" | |
# a3 = "TRUE" | |
# a4 = "" | |
# a5 = "a5" | |
# a6 = "a 6" | |
# a7 = "" | |
function main() { | |
ARGS=`getArgs "$@"` | |
a1=`echo "$ARGS" | getNamedArg a1` | |
a2=`echo "$ARGS" | getNamedArg a2` | |
a3=`echo "$ARGS" | getNamedArg a3` | |
a4=`echo "$ARGS" | getNamedArg a4` | |
a5=`echo "$ARGS" | getNamedArg a5` | |
a6=`echo "$ARGS" | getNamedArg a6` | |
a7=`echo "$ARGS" | getNamedArg a7` | |
echo "a1 = \"$a1\"" | |
echo "a2 = \"$a2\"" | |
echo "a3 = \"$a3\"" | |
echo "a4 = \"$a4\"" | |
echo "a5 = \"$a5\"" | |
echo "a6 = \"$a6\"" | |
echo "a7 = \"$a7\"" | |
exit 0 | |
} | |
function getArgs() { | |
for arg in "$@"; do | |
echo "$arg" | |
done | |
} | |
function getNamedArg() { | |
ARG_NAME=$1 | |
sed --regexp-extended --quiet --expression=" | |
s/^--$ARG_NAME=(.*)\$/\1/p # Get arguments in format '--arg=value': [s]ubstitute '--arg=value' by 'value', and [p]rint | |
/^--$ARG_NAME\$/ { # Get arguments in format '--arg value' ou '--arg' | |
n # - [n]ext, because in this format, if value exists, it will be the next argument | |
/^--/! p # - If next doesn't starts with '--', it is the value of the actual argument | |
/^--/ { # - If next do starts with '--', it is the next argument and the actual argument is a boolean one | |
# Then just repla[c]ed by TRUE | |
c TRUE | |
} | |
} | |
" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment