Search code examples
shellfish

In fish shell how to check if a variable is a number?


How to check if a variable is a number in fish shell? Looking for a simple way of doing it.


Solution

  • One possible solution is using string match as follows:

    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
    

    If num is not a number nothing is echo-ed.

    Here's string match synopsis from fish shell documentation (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...]