用户输入验证(While循环)非数字输入请求的数字(bash)

时间:2017-09-29 23:32:20

标签: bash validation scripting user-input delimiter

我正在尝试完成下面描述中列出的任务,但我不确定如何在确保用户输入字母,分隔符或空格作为其user_number时验证用户的响应。目前,当我运行脚本时,它会声明“./loop_test.sh:line 12:[:a:integer expression expected”。我从Youtube,教科书和这里到处都看,但似乎无法弄清楚出了什么问题......有人可以帮帮我吗?

#!/bin/bash

# Description: This script will ask the user to enter a number between 20
# and 30. If the user enters an invalid number or a non-number, it will ask
# again. The process will repeat until a satisfactory number is entered.

# Option: None

printf "Hello! Select a number between 20-30: "
read user_number

while [ "$user_number" -lt 20 ] || [ "$user_number" -gt 30 ] && [ 
"$user_number" -ne *[0-9]* ]
do
    printf "Sorry, it looks like the input you selected isn't between 20-30\n"
    printf "Please select another number: "
    read user_number
done

printf "All set! Thanks for following directions!\n"

1 个答案:

答案 0 :(得分:0)

如果您使用的是bash,则可以使用更高级的比较,例如模式:

while [[ $user_number != +([0-9]) || ...

第一个条件意味着用户输入不包含一个或多个数字