0

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, especially because some of the marks are optional and cannot be assigned to a fixed position in function's signature.

UPDATE: Example Zsh solution could be: afunc ...normal parameters... "MYDATA:1:OTHERDATA:2:" and then: local mydata="${7/(#b)*MYDATA:([^:]#):*/$match[1]}". I could write a function to hide the complex pattern code, it would work like: get_key "$7" "MYDATA"; local mydata=$REPLY. That solution works but I really want to research this and find solution that's best or useful in a specific way.

  • Why did you tag both bash and zsh which use different scripting languages? Which one do you want to use? – Julie Pelletier Sep 5 '16 at 21:37
  • @JuliePelletier: both Bash and Zsh people can answer, I'll adapt Bash code to my needed Zsh code, you have to admit that tagging "zsh" would exclude many experts – Itzie Sep 5 '16 at 21:43
  • 3
    I disagree and I also mean that you should say what you really want. If you were able to adapt the solution, you wouldn't ask for help. – Julie Pelletier Sep 5 '16 at 21:46
  • @JuliePelletier: it's about general shell limitations and coming up with nice idea how to still solve a problem, not about knowing how to write scripts. I now had one idea and included Zsh solution in question. – Itzie Sep 5 '16 at 21:48
  • Well if you're resourceful as you suggest, hinting you to use shift should get you on the right track. It is available for both shells. – Julie Pelletier Sep 5 '16 at 21:52
3

Handle the (rest of the) arguments with a loop and shift. For KEY=VALUE type arguments, something like this (in bash):

function foo {
    shift      # handle the first "fixed" arg  
    while [ -n "$1" ] ; do
        key=${1%%=*}
        val=${1#*=}
        echo "key: $key value: $val"
        shift   
    done    
}              
foo first MYDATA=2 OTHERDATA=false

Or, you could use getopts (bash builtin) to parse -x style flags:

function bar {
    OPTIND=3   # skip first two args
    local opt
    while getopts "ab:" opt; do
        if [ "$opt" = "a" ] ; then
            echo flag -a encountered
        elif [ "$opt" = "b" ] ; then
            echo flag -b with arg $OPTARG
        fi
    done
}

bar fixed args -a -b foo
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.