The below bash script that takes two numbers as input from the user, compares them and check if entered number is numeric or not, and prints the larger number.
#!/bin/bash # This is a bash script to compare two numbers and print the larger one. # Function to compare two numbers compare_numbers(){ result=$(echo "$1 > $2" | bc -l) if [ "$result" -eq 1 ]; then echo "$1 is greater than $2." else echo "$1 is not greater than $2." fi } # Input prompt for the first number read -p "Enter the first number: " num1 # Input prompt for the second number read -p "Enter the second number: " num2 # Check if input is numeric if ! [[ $num1 =~ $re ]] || ! [[ $num2 =~ $re ]]; then echo "Please enter valid numeric values." exit 1 fi # Call the function to compare numbers compare_numbers $num1 $num2
Explanation:
1. Function “compare_numbers”:
This function takes two parameters (numbers) and uses the “if” statement to compare them. It prints a message indicating which number is larger or if they are equal.
Also, the compare_numbers function uses bc to perform the floating-point comparison. The -l flag is used to load the math library in bc for more advanced mathematical operations, including floating-point arithmetic. The result of the comparison is then checked, and the appropriate message is printed.
Keep in mind that using external tools may have some overhead, and you need to make sure these tools are available on the system where your script is running. If high precision or complex floating-point arithmetic is required, using more specialized programming languages like Python might be a better choice.
Note :
Bash itself does not directly support floating-point arithmetic within the context of the (( … )) construct for conditional statements. The (( … )) construct is specifically designed for integer arithmetic. If you attempt to use floating-point numbers in an arithmetic context within (( … )), you may encounter unexpected behavior or errors.
However, you can leverage other tools or external commands to perform floating-point arithmetic in Bash. One common approach is to use external commands like bc (an arbitrary-precision calculator language) or awk (a text processing and pattern matching tool) as mentioned in above bash script.
2. Input prompts:
The script uses the “read” command to prompt the user to enter the first and second numbers.
3. Input validation:
The script checks if the entered values are numeric using a regular expression. If the input is not numeric, it prints an error message and exits.
Let’s break down the regular expression “^[+-]?[0-9]+([.][0-9]+)?$”:
“^”:
– Anchors the regex at the beginning of the line, ensuring that the match starts from the beginning.
“[+-]?”:
– “[…]”: Character class. It matches any single character inside the brackets.
– “+-”: The “+” and “-” characters.
– “?”: Indicates that the preceding character class “[+-]” is optional. This means that the input can have an optional positive or negative sign.
“[0-9]+”:
– Another character class, this time matching any digit from 0 to 9.
– “+”: Requires that there is at least one digit, but there can be more.
“([.][0-9]+)?”:
– “([.][0-9]+)”: This is a group that matches a period (“.”) followed by one or more digits.
– “?”: The entire group is optional. This means that the decimal part is not required, but if present, it should consist of a period followed by at least one digit.
“$”:
– Anchors the regex at the end of the line, ensuring that the match extends to the end.
Putting it all together, the regular expression “^[+-]?[0-9]+([.][0-9]+)?$” describes a pattern for a numeric value that can be positive or negative. It allows for an optional decimal part, ensuring that the entire input string represents a valid number. Here’s how it works:
– “123”: Matches a positive integer.
– “-45”: Matches a negative integer.
– “3.14”: Matches a positive decimal number.
– “-0.001”: Matches a negative decimal number.
– “+42.8”: Matches a positive decimal number with an explicit positive sign.
– “abc”: Does not match, as it contains non-numeric characters.
– “12.34.56”: Does not match, as it contains more than one decimal point.
This regular expression is often used for basic number validation in input fields, ensuring that the entered value is a valid number format.
Let’s break down the expression “if ! [[ $num1 =~ ^[0-9]+$ ]] || ! [[ $num2 =~ ^[0-9]+$ ]];” into its components:
“[[ $num1 =~ ^[0-9]+$ ]]”:
– “[[ … ]]”: Double square brackets denote the extended test command in bash.
– “$num1”: This is the variable containing the user input for the first number.
– “=~”: The regex matching operator.
– “^[0-9]+$”: This regular expression ensures that the entire string consists only of digits (0-9).
So, “[[ $num1 =~ ^[0-9]+$ ]]” checks if “$num1” is a string consisting of only numeric characters.
“! [[ $num1 =~ ^[0-9]+$ ]]”:
– The “!” at the beginning negates the result of the expression inside the double brackets. So, it checks if “$num1” is not a string consisting of only numeric characters.
“||”:
– The double pipe “||” is a logical OR operator in bash. It returns true if at least one of the conditions on either side is true.
“! [[ $num2 =~ ^[0-9]+$ ]]”:
– Similar to the first part, this checks if “$num2” is not a string consisting of only numeric characters.
Putting it all together, the entire expression checks whether either “$num1” or “$num2” is not a string consisting of only numeric characters. If either of them fails this condition (i.e., if they contain non-numeric characters), the script will print an error message and exit, ensuring that the input is valid numeric data before proceeding with the comparison. This prevents unexpected behavior that could occur if non-numeric values are used in the comparison, which might lead to incorrect results or errors.
4. Calling the comparison function:
The script calls the “compare_numbers” function with the entered numbers as arguments.
To run the script, save it to a file (e.g., “compare_numbers.sh”), give it execute permissions (“chmod +x compare_numbers.sh”), and then run it (“./compare_numbers.sh”).
How do you feel about this post? Drop your comments below..