How to check if a number is within a range in shel

2019-02-22 22:04发布

问题:

I want to just insert number between two values, and otherwise the script repeated until correct number.

This is my script and it is 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

回答1:

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:

  • Test whether string is a valid integer
  • How to use double or single brackets, parentheses, curly braces


回答2:

Your if statement:

if [ $number -ge 2 && $number -ls 5 ]; then 

should be:

if [ "$number" -ge 2 ] && [ "$number" -le 5 ]; then

Changes made:

  • Quoting variables is considered good practice.
  • ls is not a valid comparison operator, use le.
  • Separate single-bracket conditional expressions with &&.

Also you need a shebang in the first line of your script: #!/usr/bin/env bash



回答3:

if [ $number -ge 2 && $number -ls 5 ]; then

should be

if [[ $number -ge 2 && $number -le 5 ]]; then

see help [[ for details



回答4:

2 changes needed.

  1. Suggested by Sergio.

    if [ "$number" -ge 2 ] && [ "$number" -le 5 ]; then

  2. There is no need of break. only meaningful in a for, while, or until loop



标签: bash shell sh