1

I would like to share a way to check a string is a number in bash. This question has already been asked here, but the answer fits only for either integers or floats in classical format, when a number can be in scientific format, and it uses complex regex. Second, I don't have enough reputation to answer the existing question (totally fresh account here...).

So the question is:

How to (Easily) Check a String is a Number in bash?

with the string being like:

"1234"
"-1.234"
"1.23e4"
"+1.23E04"
etc.

Answer in the... answer below.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
taalf
  • 31
  • 4
  • Please check if the question already exists before opening a new one. See [How do I test if a variable is a number in Bash?](https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash#3951175) – Zrin Mar 27 '20 at 10:12
  • See https://stackoverflow.com/a/22106305/1745001. – Ed Morton Mar 27 '20 at 13:44
  • Zrin, I explain why I opened a new one in the text of the question (not enough reputation to answer existing thread). – taalf Mar 27 '20 at 17:02
  • Ed Morton, yes, I saw this one afterwards and indeed it's the same logic. Too bad it's lost in the flow of answers. The accepted one is not the best. Then, I think "returning" (printing) "true" or "false" is better than 1 or 0, because its a boolean. With the present solution, this works: if IsNumber $var; then (...) fi. – taalf Mar 27 '20 at 17:03

1 Answers1

2

An easy way is to use awk like this:

function IsNumber {

    echo "$1" | awk '{if ($1+0 == $1) print "true"; else print "false"}'

}

Examples:

$ IsNumber 1234
true
$ IsNumber 1.234
true
$ IsNumber 1.23E04
true
$ IsNumber abc
false
taalf
  • 31
  • 4
  • The idiomatic way to tell awk to treat a strnum (e.g. $1) as a number is to add zero and so the idiomatic awk code to test for $1 being a number is `$1+0 == $1` rather than `$1*1 == $1`. – Ed Morton Mar 27 '20 at 13:59
  • Hi Ed Morton. Is this a question of style or is there an advantage to take +0 instead of *1? (eg. is it quicker?) – taalf Mar 27 '20 at 17:06
  • 1
    idk, I've been using it for 30+ years and haven't thought about it... I suppose MAYBE addition is faster than multiplication or maybe `+0` has less floating point rounding error possibility than `*1`? The main argument for using it AFAIK is that everyone knows exactly what it is when they see it since it's what's been used for years in scripts. – Ed Morton Mar 27 '20 at 17:09
  • 1
    Thanks for the info Ed Morton. – taalf Mar 27 '20 at 17:14