bash 如何检查一个数字是否在shell中的范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50521798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:55:37  来源:igfitidea点击:

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

bashshellsh

提问by Hyman

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

采纳答案by codeforester

If you are using Bash, you are better off using the arithmetic expression, ((...))for readability and flexibility:

如果您使用 Bash,((...))为了可读性和灵活性,最好使用算术表达式:

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)).

((number >= 2 && number <= 5))也可以写成((2 <= number <= 5))



See also:

也可以看看:

回答by sergio

Your if statement:

您的 if 语句:

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.
  • lsis not a valid comparison operator, use le.
  • Separate single-bracket conditional expressions with &&.
  • 引用变量被认为是很好的做法
  • ls不是有效的比较运算符,请使用le.
  • &&.分隔单括号条件表达式。

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

您还需要在脚本的第一行中有一个 shebang: #!/usr/bin/env bash

回答by Diego Torres Milano

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

should be

应该

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

see help [[for details

help [[详细内容

回答by Jayesh Dhandha

2 changes needed.

需要进行 2 次更改。

  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

  1. 由塞尔吉奥推荐。

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

  2. 没有必要breakonly meaningful in a for, while, or until loop