Here is a generic simple command argument interface that you can insert at the beginning of all your scripts.
#!/bin/bash declare -A flags declare -A booleans args=() while [ "$1" ]; do arg=$1 if [ "${1:0:1}" == "-" ] then shift rev=$(echo "$arg" | rev) if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ] then bool=$(echo ${arg:1} | sed s/://g) booleans[$bool]=true echo \"$bool\" is boolean else value=$1 flags[${arg:1}]=$value shift echo \"$arg\" is flag with value \"$value\" fi else args+=("$arg") shift echo \"$arg\" is an arg fi done echo -e "\n" echo booleans: ${booleans[@]} echo flags: ${flags[@]} echo args: ${args[@]} echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}" echo -e "\nFlag: myFlag => ${flags["myFlag"]}" echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"
By running the command:
bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f
The output will be like this:
"firstArg" is an arg "pf" is boolean "-myFlag" is flag with value "my flag value" "secondArg" is an arg "Ct" is boolean "thirdArg" is an arg "f" is boolean booleans: true true true flags: my flag value args: firstArg secondArg thirdArg Boolean types: Precedes Flag(pf): true Final Arg(f): true Colon Terminated(Ct): true Not Mentioned(nm): Flag: myFlag => my flag value Args: one => firstArg, two => secondArg, three => thirdArg
Basically, arguments are divided into logical flags and general arguments. By doing this in this way, the user can set flags and booleans anywhere, as long as he / she saves the general arguments (if any) in that order.
Let me and now you never have to deal with parsing bash arguments again!
You can view the updated script here
This has been extremely helpful over the past year. Now it can simulate the scope by adding variables to the scope parameter.
Just name the script as
replace() ( source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@" echo ${replaceFlags[f]} echo ${replaceBooleans[b]} )
It doesn't look like I implemented the scope of the argument, not sure why, I think, I don't need it yet.
jozsef morrissey Sep 03 '18 at 22:04 2018-09-03 22:04
source share