Test for string equality / string comparison in Fish shell?

How do you compare two strings in Fish (like "abc" == "def" in other languages)?

So far, I've used a combination of contains (turns out that contains "" $a only returns 0 if $a is the empty string, although that hasn't seemed to work for me in all cases) and switch (with a case "what_i_want_to_match" and a case '*'). Neither of these methods seem particularly... correct, though.


  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

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