In this tutorial we will show you how to check if bash variable is a number. This can be done very easily through the terminal application present in Linux where you can enter your commands and check if the output is according to your needs and expectations. You can moreover on enter letters in your code to test further if your bash is a number or not.
To understand how in Linux, in bash to check variable follow the steps given below.
Step 1 – Use regular expression
First of all, to make sure that the given input is a valid integer we are using a regular expression. This regular expression states that any character which comes in between 0 to 9 is allowed. In addition to that the “exponential sign along with the dash” states that the negative numbers are also allowed. If you want to make the regular expression for the positive numbers just remove the dash sign.
Over here, we have used the echo command and have given it a positive number.
echo 20 | grep “^-\?[0-9]*$”
Step 2 – View the printed number
With that done, you will see that it will print 20 in the terminal, in red color. That means, it has been validated as a positive number by our regular expression. It shows that here bash is a number.
Step 3 – Type letters in the code
Notice that over here, if we type “abc” after the “echo” command, it will not show any output on the terminal. This is because “abc” is not a numeric value.
And there you have it; a basic code written in bash to check variable that whether the input is a number.
echo abc | grep “^-\?[0-9]*$”