shell基础知识6-在不按回车键的情况下读入N个字符

Bash命令 read 能够从键盘或标准输入中读取文本。我们可以使用 read 以交互的形式读取用
户输入,不过 read 能做的可远不止这些。编程语言的大多数输入库都是从键盘读取输入,当回
车键按下的时候,标志着输入完毕。但有时候是没法按回车键的,输入结束与否是由读取到的字
符数或某个特定字符来决定的。例如在交互式游戏中,当按下 + 键时,小球就会向上移动。那么
若每次都要按下 + 键,然后再按回车键来确认已经按过 + 键,这就显然太低效了。

read 命令提供了一种不需要按回车键就能够搞定这个任务的方法。

限制输入的字符串

下面的语句从输入中读取10个字符并存入变量testRead

[root@dns-node2 ~]# read -n 10 testRead
1234567891[root@dns-node2 ~]# echo $testRead
1234567891

无回显的方式读取密码
[root@dns-node2 ~]# read -s pwd
[root@dns-node2 ~]# echo $pwd
nihao
显示提示信息以及限时读取
[root@dns-node2 ~]# read -s -t 10 -p "Enter you pwd >" testIn
Enter you pwd >[root@dns-node2 ~]# echo $testIn
1234
自定义结束符
[root@dns-node2 ~]# read -d ";" -p "input your name" Testd
input your namehello
what's your name ;[root@dns-node2 ~]# echo $Testd
hello what's your name
posted @ 2019-09-16 23:19  温柔易淡  阅读(481)  评论(0编辑  收藏  举报