Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

bash - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...