在fish shell中如何检查变量是否是数字?

gma*_*gno 4 shell fish

在fish shell中如何检查变量是否为数字?寻找一种简单的方法来做到这一点。

gma*_*gno 7

一种可能的解决方案是使用string match如下:

for arg in 9 -42 0 3.14159 stack overflow hyphenated-word 922-99999 0...0 555.555.555
    if string match -qr '^-?[0-9]+(\.?[0-9]*)?$' -- "$arg"
        echo $arg is a number
    end
end

9 is a number
-42 is a number
0 is a number
3.14159 is a number
Run Code Online (Sandbox Code Playgroud)

如果num不是数字,则不会回显任何内容。

以下是string matchFish shell 文档的概要(https://fishshell.com/docs/current/commands.html#string):

string match [(-a | --all)] [((-e | --entire)] [(-i | --ignore-case)] [(-r | --regex)]
         [(-n | --index)] [(-q | --quiet)] [(-v | --invert)] PATTERN [STRING...]
Run Code Online (Sandbox Code Playgroud)