Jonathan
Jonathan

Reputation: 11321

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

Upvotes: 19

Views: 6851

Answers (1)

faho
faho

Reputation: 15984

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.

Upvotes: 36

Related Questions