Search code examples
fish

How can I test whether a string contains another string in fish shell?


How do I test for the presence of a substring in fish shell? For instance, within a switch expression:

 set myvar "a long test string"
 switch $myvar
 case magical-operator-here "test string" 
     echo 'yep!'
 case '*'
     echo 'nope!'
 end

Solution

  • The * is the wildcard character, so

    set myvar "a long test string"
    switch $myvar
    case "*test string" 
        echo 'yep!'
    case '*'
        echo 'nope!'
    end
    

    If you wish to test if it ends with that string. If it can also appear somewhere in the middle, add another * at the end.

    Also, since 2.3.0, fish has had a string builtin with a match subcommand, so you could also use string match -q -- "*test string" $myvar. It also supports pcre-style regexes with the "-r" option.