Shell Script To Check For a Valid Floating-Point Value
Last Updated :
20 Apr, 2021
User Input can be hectic to manage especially if it's about numbers. Let's say you wanted to perform mathematical calculations in your app or script. It's not hard to say that it will have to deal with floating-point numbers. It's easy in many statically typed programming languages but if it has to do in terminals then that can get quite annoying as shell scripting or bash doesn't have any data types.
We have to deal without data types and make use of programming skills to actually make it work. Hopefully, we have regular expressions in Bash to deal with such problems. Regular Expressions or RegEx, in short, is an expression as the name suggests that can find certain patterns in a text field. It quite a powerful tool to have in a Programmer's toolkit. So, let's see how to solve the problem.
Approach
So let's find a modular approach to the problem statement. We need to check whether the input variable is a decimal (floating-point) number or not. To do that we must have only digits in the variable and just a single decimal point. The decimal point can be anywhere, but it has to be only one. To check if only digits are present we can use Regular Expression and further we can also check for a decimal point from the second to the second-last character as a decimal point cannot be in the beginning and at the end. We can simply use conditional statements to verify these necessary conditions.
Explanation
Firstly we will take the user input and store it in any preferable named variable.
We are using read to prompt the user for input. Along with the "read" command we will be using -p as an argument to the base "read" command for a prompt that displays the text such as enter the number or any preferable relevant information.
Now we need to check that the input is a number or not. This allows us to be sure for the next condition to be a floating-point value otherwise it will conflict with numbers and floating-point numbers.
Regular Expression:
Regular Expression allows us to find a pattern in the text or a variable. Here we are using n as an input variable. We use =~ to make bash aware that the coming expression is a RegEx. After that, we use ^ and $ for checking the pattern from start to end.
A number can have positive or negative signs so does a floating value and hence it is applied to both conditions. Anything between [ ] has to match with the input, in this case, we include 0-9 as any number can be in the input. We have added a "?" after the +- signs to make those optional i.e. it's not mandatory to include + to indicate the numbers as positive. An * sign to repeat the previous expression zero times or more times as to include more digits furthermore. After a number is being identified we use "+" to include the following conditions to the preceding once or more times. The "\" in the floating-point condition is just behaving to turn as an ordinary character. We finally add ".' between "\" and "?" to merge the expressions and to make decimal optional, but it won't call a number as the condition is already satisfied by the previous if condition. Hence, we end the expression with the "$" sign and print the satisfied condition of the input being an integer, floating-point value, or any expression.
Shell Script Code Snippet
#!/bin/bash
# User Input
read -p "Enter the number : " n
# Check for a number
if [[ $n =~ ^[+-]?[0-9]+$ ]];then
echo "The Input is an integer."
# Check for a floating number
elif [[ $n =~ ^[+-]?[0-9]*\.?[0-9]+$ ]];then
echo "Input is a float "
else
echo "The input is not a number."
fi
Output:
ShellScript Output with many test-cases
By making a Shell Script using Regular Expression we verified a user input to be a floating-point number or not. The script doesn't consider scientific notation as a floating-point value that also can be achieved but to keep it simple for simplistic use this is working accurately.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Linux/Unix Tutorial Linux is one of the most widely used open-source operating systems. It's fast, secure, stable, and powers everything from smartphones and servers to cloud platforms and IoT devices. Linux is especially popular among developers, system administrators, and DevOps professionals.Linux is:A Unix-like OS
10 min read