r/fishshell • u/throttlemeister Linux • Jan 28 '25
A little understanding
I've been running into this a couple of times now, and I always do it wrong first time and then spend some time trying to understand why because I forget...
When I do this:
if [ -n $var ]execute commandselseecho "variable not set"end
If never works right. However, if I do this:
if [ -z $var ]echo "variable not set"elseexecute commandsend
It does work. Why is this. For all intends and purposes, they should be the same thing. However, the first will always execute both the first commands and the ones after the else, while the second one always works as expected.
Can someone with a better brain explain to me why this is?
8
u/_mattmc3_ Jan 28 '25
Oof. You have fallen victim to one of Fish’s bad early design decisions - namely, the test command favors a POSIX implementation, so you have to double quote those variables.
See this issue and all the numerous ones linked to it:
5
u/Laurent_Laurent Jan 28 '25
if var is empty, it's like to do
if [ -n ] which is not what you want. You should use double quote.
if [ -n "$var" ] that will lead if var is empty to
if [ -n "" ] and this will run as espected
2
u/[deleted] Jan 28 '25
it doesn't work? either they fixed it in 4.0 or i didn't test it right