Search code examples
shellfish

What is the meaning of '-*' as case parameter in a fish shell script?


The official documentation of fish shell has this example.

function mkdir -d "Create a directory and set CWD"
    command mkdir $argv
    if test $status = 0
        switch $argv[(count $argv)]
            case '-*'

            case '*'
                cd $argv[(count $argv)]
                return
        end
    end
end

I understand case '*' is like default: in C++ switch statement.

What is the meaning or usage of case '-*'?


Solution

  • It's a glob match.

    case '-*' will be executed whenever the switched parameter starts with a "-".

    And because only the first matching case will be used, case '*' as the last case is like "default:". If you had it earlier, it would swallow all cases after it.

    Also the quotes here are necessary because otherwise fish would expand that glob, which would mean case -* would have all matching filenames in the current directory as parameters, so it would be true if the switched parameter is the name of a file in the current directory that starts with "-".