在 fish shell 脚本中作为 case 参数的 '-*' 是什么意思?

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

fish shell 的官方文档有 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

我理解 case '*' 类似于 C++ switch 语句中的 default:

case '-*'的含义或用法是什么?

这是一个全局匹配。

case '-*'只要切换的参数以“-”开头就会执行。

并且因为只使用第一个匹配的案例,所以 case '*' 最后一个案例就像 "default:"。如果你早点拥有它,它会吞下它之后的所有案例。

此处的引号也是必要的,否则 fish 会扩展该 glob,这意味着 case -* 会将当前目录中的所有匹配文件名作为参数,因此如果切换参数是当前目录中以“-”开头的文件名。

的帮助下,明白了-*的用意。

-* 是全局模式。它与 *.pdfReport_2016_*.

等模式完全不同

作者添加了此检查以忽略所有以 - 开头的目录。它将创建一个以 - 开头的目录,但不会为其设置 CWD。

原因,-在shell中有特殊用途。

例如,cd - 不会将目录更改为名为 - 的目录。相反,它会切换到您所在的最后一个目录。

名称以 - 开头的目录或文件是麻烦的来源。 SO姐妹网站上的以下问题给出了一个想法。

  1. How do you enter a directory that's name is only a minus?

  2. How do I delete a file whose name begins with “-” (hyphen a.k.a. dash or minus)?

  3. How to cd into a directory with this name “-2” (starting with the hyphen)?

难怪作者决定忽略以 -.

开头的目录