DISQUS

Tech-Recipes: Checking if a variable is a number in ksh | Korn shell | Tech-Recipes

  • nacho_a · 1 year ago
    What if $1 is 0?
    You'll get FALSE!

    From expr's man page:

    EXIT STATUS
    [...]
    0 if the expression is neither NULL nor 0
    1 if the expression is either NULL or 0

    [...]
    I'd use "-eq 2" instead of "-ne 0."

    Thanks anyway, good tip.
  • Mr. KIPS · 11 months ago
    I wouldn't play with the exit status. Instead, change the arithmetic expression. Use expr $1 +1.
  • Andrew · 8 months ago
    I'm not sure if anyone will read this, but to check if a variable is a number in ksh, it would take 1 expression, there is no reason to add, subtract or do any arithmetic. Example of a script:

    G_VAR=$1
    if [[ $G_VAR = +([0-9]) ]]; then
    print "G_VAR is a number"
    else
    print "G_VAR is not a number"
    fi