Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following solution can also be used in basic shells such as Bourne without the need for regular expressions. Basically any numeric value evaluation operations using non-numbers will result in an error which will be implicitly considered as false in shell:</p> <pre><code>"$var" -eq "$var" </code></pre> <p>as in:</p> <pre><code>#!/bin/bash var=a if [ "$var" -eq "$var" ] 2&gt;/dev/null; then echo number else echo not a number fi </code></pre> <p>You can can also test for $? the return code of the operation which is more explicit:</p> <pre><code>"$var" -eq "$var" 2&gt;/dev/null if [ $? -ne 0 ]; then echo $var is not number fi </code></pre> <p>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.</p> <p><strong>CAVEATS</strong> (thanks to the comments below):</p> <ul> <li>Numbers with decimal points are <em>not</em> identified as valid "numbers"</li> <li>Using <code>[[ ]]</code> instead of <code>[ ]</code> will always evaluate to <code>true</code></li> <li>Most non-Bash shells will always evaluate this expression as <code>true</code></li> <li>The behavior in Bash is undocumented and may therefore change without warning</li> <li>If the value includes spaces after the number (e.g. "1 a") produces error, like <code>bash: [[: 1 a: syntax error in expression (error token is "a")</code></li> <li>If the value is the same as var-name (e.g. i="i"), produces error, like <code>bash: [[: i: expression recursion level exceeded (error token is "i")</code></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload