检查用户输入是否正确 [英] Check user input is correct

查看:129
本文介绍了检查用户输入是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个bash脚本,该脚本通过用户输入获取数字进行计算.我遇到的问题是,如果用户错误输入字母或空格,则整个脚本将失败,并且用户必须重新启动.

I wrote a bash script which takes numbers for calculation via user input. The problem I have is if the user types a letter or a space by mistake, the whole script fails and the user must start again.

必须有一种简单的方法来检查输入是否为数字,如果意外输入了其他内容,则会再次要求输入?

There must be an easy way to check the input is numeric only that will ask for the input again if anything else is input accidentally?

推荐答案

使用while循环

number=""
while [[ ! $number =~ ^[0-9]+$ ]]; do
    echo Please enter your age
    read number
done
echo You are $number years old

这篇关于检查用户输入是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆