michelpm
michelpm

Reputation: 1845

In fish shell, how can I put two conditions in an if statement?

What I want to do using bash:

> if true; then echo y; else echo n; fi
y
> if false; then echo y; else echo n; fi
n
> if false || true; then echo y; else echo n; fi
y

Now trying with fish:

> if true; echo y; else; echo n; end
y
> if false; echo y; else; echo n; end
n

# Here 'or true' are just two arguments for false
> if false or true; echo y; else; echo n; end 
n

# Here 'or true;' is a command inside the if
> if false; or true; echo y; else; echo n; end 
n

# Can't use command substitution instead of a command
> if (false; or true); echo y; else; echo n; end
fish: Illegal command name “(false; or true)”

How can I have two conditions in an if?

Upvotes: 29

Views: 10928

Answers (4)

terje
terje

Reputation: 4424

Two other approaches:

Approach one:

    if begin false; or true; end
      echo y
    else
      echo n
    end

Approach two:

    false; or true
    and echo y
    or echo n

Upvotes: 31

MAChitgarha
MAChitgarha

Reputation: 4288

For anyone looking for testing expressions: You can do something like the following (if $i is lower than $m or greater than $n):

if [ $i -lt $m ] || [ $i -gt $n ]
    echo "Voila!"
end

Upvotes: 0

Aurelio Jargas
Aurelio Jargas

Reputation: 390

Since fish 2.3b1, one can directly chain commands in the if condition with and/or. The begin ... end is not necessary anymore. The official docs were updated in May 2016.

So now this works as expected:

> if false; or true; echo y; else; echo n; end
y

Upvotes: 3

michelpm
michelpm

Reputation: 1845

This way works, but it is an ugly hack:

> if test (true; and echo y); echo y; else; echo n; end 
y
> if test (false; and echo y); echo y; else; echo n; end 
n
> if test (false; or true; and echo y); echo y; else; echo n; end 
y

I sincerely hope for better answers.

Upvotes: 2

Related Questions