shell 如何在bash中检查一个数字是否在动态范围之外?

bnl4lu3b  于 2023-06-24  发布在  Shell
关注(0)|答案(1)|浏览(97)

我有一个比萨饼制造商代码。它让用户选择一个比萨饼的大小和一个列表的浇头从一个副文件。我试图验证用户的输入,以便它可以输入一个数字之间的 * 1 * 和 * 金额的浇头 * 从副文件。
我从文件中获取行数,并使用wc numtop=$( cat Toppings | wc -l );将其设置为变量
之后,我读取用户输入并使用if运行检查

read topp
if [[ "$topp" < 1 || "$topp" > "$numtop" ]]; then
     echo "Enter from 1 to " $numtop
else
     echo "Good choice"
fi

但它只允许我输入1或$numtop变量中的数字。我不明白为什么这行不通。

6yoyoihd

6yoyoihd1#

你需要使用(( )) for arithmetic表达式,类似于:

#!/usr/bin/env bash

numtop="$(wc -l < Toppings)"

while read -rp "Enter from 1 to  $numtop " topp; do
  if (( topp < 1 || topp > numtop )); then
    echo "Enter from 1 to $numtop"
  else
    echo "Good choice"
    break
  fi
done

编辑:按照@jhnc,给定输入是这样的:a[$(date>/dev/tty)],1(第一个答案严重中断)首先检查输入的值是否是严格的数字。

#!/usr/bin/env bash

##: Test also if Toppings is empty if it is a file
##: or just test the value of $numtop.
numtop="$(wc -l < Toppings)"

while printf 'Enter from 1 to %s ' "$numtop"; do
  read -r topp
  case $topp in
    ('')
      printf 'input is empty\n' >&2
       ;;
    (*[!0123456789]*)
       printf '%s has a non-digit somewhere in it\n' "$topp" >&2
       ;;
    (*)
      if (( topp < 1 || topp > numtop )); then
        printf 'You entered %s\n' "$topp"  >&2
      else
        printf 'You entered %s Good choice!\n' "$topp" &&
        break
      fi
     ;;
  esac
done

相关问题