Last active
August 29, 2015 14:05
-
-
Save lyuboraykov/1f47c58e791c025d1837 to your computer and use it in GitHub Desktop.
Parse long command line arguments in Bash
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
#!/usr/bin/env bash | |
# Console-line parameter parsing script. | |
# Specify options in the OPTS variable in the following format: | |
# whitespace sepparated values | |
# OPTS="--<argument_name> --<argument_with_value>= --!<mandatory_argument>=" | |
# Then it creates variables in the format: OPTS_<ARGUMENT_NAME_IN_CAPS> | |
# If the argument doesn't need value to be provided assings 0 or 1. | |
# If the argument needs value but none is provided a 0 is assigned | |
#SCRIPT START | |
OPTS="--argument --anotherarg --!thirdarg= --fourtharg=" | |
IFS='--' read -ra args <<< "$OPTS" && for i in "${args[@]}"; do | |
if [ ! -z $i ]; then | |
ARG_NAME="${i//[=! ]/}" | |
ARG_VALUE=$(printf -- '%s\n' "${@}" | grep -- "--$ARG_NAME") | |
if [[ "$i" =~ ^.*=\ ?$ ]]; then | |
if [ -z "${ARG_VALUE##--$i}" ]; then | |
[[ "$i" == *!* ]] && echo "$ARG_NAME is mandatory!" && exit 1 | |
printf -v "OPTS_${ARG_NAME^^}" "0" | |
else | |
printf -v "OPTS_${ARG_NAME^^}" "${ARG_VALUE##--$ARG_NAME=}" | |
fi | |
else | |
[ -z "${ARG_VALUE##--$i}" ] ; ARG_VALUE=$? | |
printf -v "OPTS_${ARG_NAME^^}" "$ARG_VALUE" | |
fi | |
fi | |
done | |
# SCRIPT END | |
echo "OPTS_ARGUMENT: $OPTS_ARGUMENT" | |
echo "OPTS_ANOTHERARG: $OPTS_ANOTHERARG" | |
echo "OPTS_THIRDARG: $OPTS_THIRDARG" | |
echo "OPTS_FOURTHARG: $OPTS_FOURTHARG" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment