Matching the real numbers

To find out whether a given number is real or not, simply we can change the rule of the regular expression. We will also add the sign (+ or -) to accept the signed numbers. We will combine the whole expression in a single if statement and check for its validity.

Script:

echo "Hello World";

read -p "Enter a number: " NUM
 
if [[ $NUM =~ ^[+-]?[0-9]+([.][0-9]+)?$ ]]; then
   echo "${NUM} is a real number"
else
   echo "${NUM} is not real number"
fi

Explanation

We will read the variable values from the user and store them in “NUM”. An equal tilde (=~) is used for comparison to check the entered value. We have used regular expressions to find the validity of real numbers. The expression also checks real numbers with a sign (+ or -). Output the result depending upon the input.

Output 1:

The user is prompted to enter a number using a read. In test case #1 we will enter a  “*32.34 ” (which is not a real number). “If ” returns false and jumps to the else part. Output is printed as “*32.34 ” is not a number” 

 

Output 2:

The user is prompted to enter a number using a read. In test case #2 we will enter a  “-7448.35 ” (which is a signed real number). “If ” returns true and output is printed as “7448.35 ” is not a number”.

 

Conclusion:

The proposed solution checks whether the given input is a number or not. It uses regular expressing using if-else statements or using switch-case execution. 



How to Check if a Variable Is a Number in Bash

A number contains a combination of digits from 0-9. All the variables in Bash are treated as character strings but the arithmetic operations and comparisons are allowed even when it is stored in the string format. But before performing any arithmetic operations, we need to check if the stored value is a valid number. To check whether the entered variable is a number, we have to verify that the value contains only digits 

Similar Reads

Using regular expression with equal tilde operator (=~)

It is one of the easiest and quickest ways to check if the value is a number or not. The equal tilde (=~) operator is used for comparing the value entered by a user with a regular expression. Bash scripting uses an “if” statement to do the comparison...

Check using the switch case

To check whether the given output is a number, the alternative way is to use a case statement. It behaves similarly to the switch statement we use in other programming languages. While there are multiple ways to do so, we will use regular expressions in the case statement to verify if a given input is a number or not....

Matching the real numbers

To find out whether a given number is real or not, simply we can change the rule of the regular expression. We will also add the sign (+ or -) to accept the signed numbers. We will combine the whole expression in a single if statement and check for its validity....