In the fish shell the syntax for conditionals is hard to find. Does anyone have a link to an explanation of how to write an if, with ands and ors?
In particular I would like to write
if not $status
do a command
end
To do a command when the previous command returned a non-success. How do I do that?
See http://fishshell.com/docs/current/commands.html#if and http://fishshell.com/docs/current/tutorial.html#tut_conditionals.
Fish's if structure looks like this:
if COMMAND
# do something if it succeeded
else
# do something if it failed ($status != 0)
end
Then there are also the not
, and
and or
commands, that you can use like
if not COMMAND1; or COMMAND2
# and so on
If you really want to test a variable (e.g. $status), you need to use test
as the command, like
if test $status -eq 0
Do keep in mind that $status changes after every command, so if you need to use the status of an earlier command (common in prompts) you need to do what Joachim Pileborg said, save it to another variable.
Also, test
has some issues with quotes (because it's one of the few parts of fish to adhere to POSIX) - if in test $foo -eq 0
$foo is undefined, test will error out, and if it is undefined in test -n $foo
, the test will be true (because POSIX demands that test with one argument be true).
As a sidenote, in fish versions before 2.3.0, you need to add begin
and end
around a condition with and
or or
because it was interpreted weirdly.
So you'd have to do
if begin COMMAND; or COMMAND2; end # do something for status = 0