Test for string equality / string comparison in Fish shell?
The manual for test
has some helpful info. It's available with man test
.
Operators for text strings
o STRING1 = STRING2 returns true if the strings STRING1 and STRING2 are identical.
o STRING1 != STRING2 returns true if the strings STRING1 and STRING2 are not
identical.
o -n STRING returns true if the length of STRING is non-zero.
o -z STRING returns true if the length of STRING is zero.
For example
set var foo
test "$var" = "foo" && echo equal
if test "$var" = "foo"
echo equal
end
You can also use [
and ]
instead of test
.
Here's how to check for empty strings or undefined variables, which are falsy in fish.
set hello "world"
set empty_string ""
set undefined_var # Expands to empty string
if [ "$hello" ]
echo "not empty" # <== true
else
echo "empty"
end
if [ "$empty_string" ]
echo "not empty"
else
echo "empty" # <== true
end
if [ "$undefined_var" ]
echo "not empty"
else
echo "empty" # <== true
end
if [ "abc" != "def" ]
echo "not equal"
end
not equal
if [ "abc" = "def" ]
echo "equal"
end
if [ "abc" = "abc" ]
echo "equal"
end
equal
or one liner:
if [ "abc" = "abc" ]; echo "equal"; end
equal