jack
jack

Reputation: 581

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

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

Upvotes: 42

Views: 91540

Answers (6)

Pinak Mazumdar
Pinak Mazumdar

Reputation: 59

while :; do read option if [[ $option -ge 1 && $option -lt 4 ]]; then echo "correct" c break else echo "Incorrect option selected,choose an option between [1-4]" fi done

Upvotes: 0

Sam
Sam

Reputation: 17

Try bellow code

echo "Enter number" 

read input

  if [[ $input ]] && [ $input -eq $input 2>/dev/null ]

  then

        if ((input >= 1 && input <= 4)); then

    echo "Access Granted..."

    break

  else

    echo "Wrong code"

  fi

  else

     echo "$input is not an integer or not defined"

  fi

Upvotes: 1

codeforester
codeforester

Reputation: 42999

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:

Upvotes: 55

Jayesh Dhandha
Jayesh Dhandha

Reputation: 2119

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

Upvotes: 2

builder-7000
builder-7000

Reputation: 7627

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

Upvotes: 15

Diego Torres Milano
Diego Torres Milano

Reputation: 69218

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

should be

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

see help [[ for details

Upvotes: 5

Related Questions