Test for string equality / string comparison in Fish shell?

Fish

Fish Problem Overview


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.

Fish Solutions


Solution 1 - Fish

  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

Solution 2 - Fish

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeigh BreneckiView Question on Stackoverflow
Solution 1 - FishKeith FlowerView Answer on Stackoverflow
Solution 2 - FishDennisView Answer on Stackoverflow