Search code examples
fish

'At least one out of multiple' conditional


I want to say:

command1
command2
command3

if not at least one of these yields status code 0, then 
launch command4

The goal is to always execute all of them, and in case all fail, then execute command number 4.

I tried creating a counter, and that seems not very elegant, and all different combinations with and/or, if else and so on, also look clumsy/don't work.

How would you write this?

Thanks a lot


Solution

  • Since it appears you do want to run them eagerly - always run all statements and only run the rest if any one of them succeeded, you'll have to use a variable:

    set -l success 0
    statement1; and set success 1
    statement2; and set success 1
    statement3; and set success 1
    
    if test $success = 1
        # do your thing
    end
    

    This isn't a very common thing, typically you'd want to run it lazily - run until one succeded. That's "or":

    if statement1; or statement2; or statement3
    

    (also "statement" here would have to be a command - that's what fish's if expects)

    For example you could do:

    if test -e /etc/foo.conf; or test -e ~/.config/foo.conf; or test -e ~/.foo.conf
    

    if you wanted to test for a config file for something.