分页: 1 / 1
[已解决]bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 18:27
由 youzhiyili
已解决:8楼
----------------------------------------------
如题
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 18:47
由 YeLee
其実,本王的想法是用正则把非数字过滤掉,留下来的也只有数字了,至于read是否支持这种參数就不清楚了。

Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 20:19
由 onlylove
我的想法是先读进来,然后再判断……ascii码什么的,当然了,会不会受locale影响就不知道了(其实我觉得会……)
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 20:44
由 langyxxl
read 可以设置只读取你想读取的字母,当然数字也可以
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 20:48
由 youzhiyili
楼上两位说的太高深了,我不懂
我正在学写一个脚本,其中有一个函数是修改GRUB_TIMEOUT
如果输入数字,可以正确修改
可是如果非数字,会变成这样GRUB_TIMEOUT=0
如果直接回车,会变成这样:GRUB_TIMEOUT=
老大们帮我改改吧
代码: 全选
grub_set(){
{
grub_time=$( cat /etc/default/grub | grep GRUB_TIMEOUT | cut -c14 |tail -1)
clear
if [ "$grub_time" -gt "-1" ]; then
echo "$newline"
echo "当前 GRUB 菜单等待时间为"$grub_time"秒"
echo "你希望是几秒?输入1~10任一数字"
echo "$newline_1"
echo -ne "\E[33;1m\033[32m$warngrub\033[0m"
read new_grub_time
new_grub_time=`expr $new_grub_time + 0 2> /dev/null`
oldtime="GRUB_TIMEOUT="$grub_time""
newtime="GRUB_TIMEOUT="$new_grub_time""
sed -i 's/'$oldtime'/'$newtime'/' /etc/default/grub && update-grub
fi
}
}
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-19 21:23
由 youzhiyili
langyxxl 写了:read 可以设置只读取你想读取的字母,当然数字也可以
怎样设置?能否写个例子?
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-20 5:46
由 poloshiao
然后再判断……ascii码
http://www.asciitable.com/
數字 : 0 ~ 9
Dec : 48 ~ 57
HX : 30 ~ 39
Oct : 060 ~ 069
在這個範圍 進入判斷 繼續
不在這個範圍 出現錯誤訊息 重新輸入
会不会受locale影响就不知道了
以下 有關 lang 的描述 看看 有沒有幫助
http://www.gnu.org/software/grub/manual ... l#Features
Have a flexible command-line interface
The list of commands (see Commands) are a subset of those supported for configuration files. Editing commands closely resembles the Bash command-line (see Command-line interface), with TAB-completion of commands, devices, partitions, and files in a directory depending on context.
Writing full configuration files directly
grub.cfg is written in GRUB’s built-in scripting language, which has a syntax quite similar to that of GNU Bash and other Bourne shell derivatives.
http://www.gnu.org/software/grub/manual/grub.html#lang
lang
If this variable is set, it names the language code that the gettext command (see gettext) uses to translate strings.
Simplified Chinese as ‘zh_CN’
http://www.gnu.org/software/grub/manual ... ml#gettext
gettext
Command: gettext string
Translate string into the current language.
http://www.gnu.org/software/grub/manual ... -interface
The flexible command-line interface
Re: bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-20 16:09
由 youzhiyili
不好意思,是我没说清楚,应该是只允许输入0~9任意数字
让大家费心了
代码: 全选
#!/bin/bash
abc(){
echo "请输入0~9任一数字"
read i
if [ "$i" -le "9" ] && [ "$i" -ge "0" ] ;then
echo "输入正确"
else
clear && echo "输入错误" && sleep 1
abc
fi
}
abc
Re: [已解决]bash:怎样让read只读取数字?或者怎样禁止输入非数字?
发表于 : 2014-02-25 21:25
由 aerofox
用 while 循环来读取,直到读到合法的数字,否则一直询问。