Reputation: 10862
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?
Upvotes: 4
Views: 3473
Reputation: 246774
The shortest short form would be
the_previous_command; or do_a_command
# ..................^^^^^
Assuming you get your $status
from "the_previous_command"
Upvotes: 2
Reputation: 15924
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
Upvotes: 8
Reputation: 409166
I use the status variable to display it on the prompt if it's non-zero. For that I use the following function:
function __pileon_status_prompt
set -l __status $status
if test $__status != 0
printf '[%s%s%s]' (set_color red) $__status (set_color normal)
end
end
As you can see I set a local variable to the value of $status
and the check that variable in the condition.
Upvotes: 1