I want to just insert number between two values, and otherwise the script repeated until correct number.
This is my script and it does not work correctly:
validation(){ read number if [ $number -ge 2 && $number -ls 5 ]; then echo "valid number" break else echo "not valid number, try again" fi } echo "insert number" validation echo "your number is" $number
There are 6 types of valid relational operators in shell scripting − == operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise. != operator is the operator that equates the values of two operators and check for their inequality.
You can use range in for loop to generate the sequence of numbers like `seq`. The range expression is defined by using curly brackets and double dots. The syntax of the range expression is shown below. Here, the value of the Start and Stop can be any positive integer or character.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.
If you are using Bash, you are better off using the arithmetic expression, ((...))
for readability and flexibility:
if ((number >= 2 && number <= 5)); then # your code fi
To read in a loop until a valid number is entered:
#!/bin/bash while :; do read -p "Enter a number between 2 and 5: " number [[ $number =~ ^[0-9]+$ ]] || { echo "Enter a valid number"; continue; } if ((number >= 2 && number <= 5)); then echo "valid number" break else echo "number out of range, try again" fi done
((number >= 2 && number <= 5))
can also be written as ((2 <= number <= 5))
.
See also:
Your if statement:
if [ $number -ge 2 && $number -ls 5 ]; then
should be:
if [ "$number" -ge 2 ] && [ "$number" -le 5 ]; then
Changes made:
ls
is not a valid comparison operator, use le
.&&
.Also you need a shebang in the first line of your script: #!/usr/bin/env bash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With