Search code examples
shellloopsfish

Zipping for loop in fish shell (loop over multiple lists)


I often write ad-hoc loops straight into the command-line to run a bunch of experiments. It's always a one-time thing, so writing a script file for it is unwanted overhead.

Often, though, I'd like to zip over a bunch of parameters, I would like to run a command somewhat like the following:

for arg1,arg2 in 256,lol 128,foo 32,bar
    ./bla --many-flags --name $arg2 --something $arg1
end

I can achieve something similar but quite brittle in fish with string (or tr delim \n in old versions) like so:

for exp in 256,lol 128,foo 32,bar
    ./bla --many-flags --name (string split ',' $exp)[2] --flag (string split ',' $exp)[1]
end

I'm wondering of anyone knows of better ways which don't require the cumbersome sub-command for each use of an argument (an argument may even be used multiple times), and even worse, the arbitrary delimiter which can cause all sorts of problems?

Ideally, I could even use it as a let like so:

for arg1,arg2 in 256,lol
    ./bla --many-flags --ame $arg2 --something $arg1
end

Solution

  • As per the comments on the question, this is not supported. The closest workaround seems to be:

    for exp in 256,lol 128,foo 32,bar
        echo $exp | read -d , arg1 arg2
        ./bla --many-flags --name $arg2 --flag $arg1
    end
    

    Not quite satisfying for regular interactive use, but I'll survive it I guess.