1

I'm having trouble understanding whether I can use wildcard globbing in an if statement in fish. This switch/case works as expected:

# correctly echos macOS on macOS
switch "$OSTYPE"
    case 'darwin*'
        echo 'macOS'
    case '*'
        echo 'not macOS'
end

However, I cannot get an if statement version of the same thing to work.

# doesn't work - prints 'not macOS' on macOS
if [ "$OSTYPE" = 'darwin*' ]
    echo 'macOS'
else
    echo 'not macOS'
end

In zsh/bash you can do something like this:

[[ $OSTYPE == darwin* ]] && echo 'macOS' || echo 'not macOS'

Or, more verbosely,

if [[ $OSTYPE == darwin* ]]
  then echo 'macOS'
  else echo 'not macOS'
fi

My question is, does fish support wildcard globbing against a variable in if statements? Am I doing this wrong? I cannot find an example in the fish docs that tells me either way.

NOTE: I'm not asking about checking $OSTYPE in fish. I know there are better ways to do that. My question is limited strictly to whether it is possible to do wildcard globbing in an if statement in fish.

mattmc3
  • 17,595
  • 7
  • 83
  • 103

1 Answers1

2

No.

Use switch like you said, or the string builtin like

if string match -q 'darwin*' -- "$OSTYPE"

The if isn't important - the command you are running in your example is [, which is an alternative name for test, which is a builtin with documentation at http://fishshell.com/docs/current/commands.html#test (or man test or help test).

faho
  • 14,470
  • 2
  • 37
  • 47
  • Part of the reason I am looking to use an `if` is that `switch` can only test a single criteria, meaning I need to use an `if`. So using the `string` utility is the only way? – mattmc3 Nov 14 '18 at 17:39
  • 2
    What @faho neglected to mention is that `test` (which `[` is just an alias for) conforms to the POSIX specification. And that spec does not allow for wildcards when testing if two strings match. The `[[` form was introduced by ksh long, long, ago and adopted by bash and other shells. That syntax provides features not allowed by POSIX. If you need to test several conditions you can do `if test whatever; and string match -q 'darwin*' -- "$OSTYPE"; echo both conditions are true; end`. – Kurtis Rader Nov 14 '18 at 20:17