linux - [Solved-5 Solutions] How to test if a variable is a number in Bash - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Code:
How to test if a variable is a number in Bash ?
Linux - Solution 1:
To use a regular expression, like this:
If the value is not necessarily an integer, consider amending the regex appropriately; for instance:
To handle negative numbers:
Linux - Solution 2:
This rejects empty strings and strings containing non-digits, accepting everything else.
Negative or floating-point numbers need some additional work. An idea is to exclude - / . in the first "bad" pattern and add more "bad" patterns containing the inappropriate uses of them (?*-* / *.*.*)
Linux - Solution 3:
as in:
Redirection of standard error is there to hide the "integer expression expected" message that bash prints out in case we do not have a number.
- Numbers with decimal points are not identified as valid "numbers"
- Using [[ ]] instead of [ ] will always evaluate to true
- Most non-Bash shells will always evaluate this expression as true
- The behavior in Bash is undocumented and may therefore change without warning
- If value includes spaces after number (e.g. "1 a") produces error, like bash: [[: 1 a: syntax error in expression (error token is "a")
- If value is the same as var-name (e.g. i="i"), produces error, like bash: [[: i: expression recursion level exceeded (error token is "i")
Linux - Solution 4:
Solutions directly parsing number formats in shell. shell is not well suited to this, being a DSL for controlling files and processes. There are ample number parsers a little lower down, for example:
Change '%f' to whatever particular format you require.
Linux - Solution 5:
This tests if a number is a non negative integer and is both shell independent (i.e. without bashisms) and uses only shell built-ins: