help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Implement a key-value deserialization or something simil


From: Greg Wooledge
Subject: Re: [Help-bash] Implement a key-value deserialization or something similar
Date: Tue, 6 Sep 2016 09:22:51 -0400
User-agent: Mutt/1.4.2.3i

On Mon, Sep 05, 2016 at 11:06:16PM +0200, Sebastian Gniazdowski wrote:
> I'm wondering how to best implement a parameter $x, say $7 ??? I mean a
> last parameter to a parameter-rich function ??? that would serve as "put
> various key-data things here to stop adding more parameters"? Possible
> call could be: afunction param1 param2 ... "MYDATA=1 OTHERDATA=true".
> It's that I need to pass bunch of simple marks on some data to a
> function and don't need reserved positional parameters for them.

There is no need to "reserve" all of the positional parameters to
a function.  Bash functions do not have strict function prototypes
(as in C).  They are all variadic.

It sounds like your function wants to take two mandatory parameters,
and then an arbitrary number of optional ones.  This is no problem at all.
Simply shift away the mandatory parameters at the beginning, and then
iterate over whatever parameters are left after that.

afunction() {
    # Two mandatory parameters.
    if (($# < 2)); then
        echo "usage: afunction param1 param2 [opt=val ...]" >&2
        return 1
    fi
    local param1=$1
    local param2=$2
    shift 2

    # Any remaining parameters are options of the form key=val.
    # Load them into an associative array.
    local -A opt
    local i key val
    for i; do
        key=${i%%=*}
        val=${i#*=}
        opt["$key"]="$val"
    done

    # Now do whatever you're supposed to do.
}



reply via email to

[Prev in Thread] Current Thread [Next in Thread]