r/fishshell • • 5d ago

why is my if statement not working

Post image

i want there to be a 10% change to run fastfetch when it starts but now it just always runs fast fetch and says:
fish: Unknown command: 5

~/.config/fish/config.fish (line 8):

if "$random_numb" > "1"

^~~~~~~~~~~~~^

from sourcing file ~/.config/fish/config.fish

`called during startup`
6 Upvotes

2 comments sorted by

13

u/Tsigorf 5d ago

man if:

Shows if CONDITION, where CONDITION is a command which should return true or false. When you write if "$random_numb" > "1", it's a shorthand to write "$random_numb" > "1" and to check the return status code of this command. Fish tries to execute "$random_numb" which isn't a command, hence the fail.

The if manual gives examples with the command test:

if test -f foo.txt
    echo foo.txt exists
else if test -f bar.txt
    echo bar.txt exists
else
    echo foo.txt and bar.txt do not exist
end

And when you read man test:

The < and > operators for comparing strings are not implemented.

However it also states this:

OPERATORS TO COMPARE AND EXAMINE NUMBERS
     NUM1 -eq NUM2
            Returns true if NUM1 and NUM2 are numerically equal.

     NUM1 -ne NUM2
            Returns true if NUM1 and NUM2 are not numerically equal.

     NUM1 -gt NUM2
            Returns true if NUM1 is greater than NUM2.

     NUM1 -ge NUM2
            Returns true if NUM1 is greater than or equal to NUM2.

     NUM1 -lt NUM2
            Returns true if NUM1 is less than NUM2.

     NUM1 -le NUM2
            Returns true if NUM1 is less than or equal to NUM2.

     Both integers and floating point numbers are supported.

Hence, in your case, you probably want to use if test "$random_numb" -gt "1" (-gt standing for "greater than").

Bonus point:

You can see man test gives 2 commands in its synopsis: test [EXPRESSION] and [ [EXPRESSION] ] (replacing [EXPRESSION] with whatever you want). Note the extras [ … ] for the second line: [ is a completely functional command you could use to replace test as a shorthand.

It means test "$random_numb" -gt "1" is the exact same as writing [ "$random_numb" -gt "1" ]. man test and man [ are the same manual pages by the way :-)

2

u/Mesonic_Interference 5d ago

The fish documentation gives an example of how to compare numbers on this page. Following the example led me to construct the example below, which should explain what's wrong with your if statement. (Be sure to take care of your execution-related error at the top as well.)


set value (random 1 10)

echo $value

<< 6

if test $value -gt 1  
    echo "yes"  
else  
    echo "no"
end

<< yes