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

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

Leave a Comment