Linux shell编程之read 命令
2017-02-05 16:10
369 查看
read命令接受用户输入,并将输入放入一个标准变量中。
基本用法如下:
使用-p选项,我们可以直接指定一个提示:
如果在使用read时没有指定变量,则read命令会将接收到的数据放置在环境变量REPLY中:
使用-s选项,能够使用户的输入不显示在屏幕上,最常用到这个选项的地方就是密码的输入。
基本用法如下:
$ cat test.sh #!/bin/bash echo -n "Enter you name: " read name echo "Hello,$name!" $ ./test.sh Enter you name: world Hello,world!这个例子中,我们首先输出一句提示,然后利用read将用户输入读取到name变量。
使用-p选项,我们可以直接指定一个提示:
$ cat test.sh #!/bin/bash read -p "Enter you name:" name echo "Hello,$name!" $ ./test.sh Enter you name:world Hello,world!read命令也可以同时将用户输入读入多个变量,变量之间用空格隔开。
$ cat test.sh #!/bin/bash read -p "Enter your name and age:" name age echo "Hello,$name,your age is $age!" $ ./test.sh Enter your name and age:tom 12 Hello,tom,your age is 12! $ ./test.sh Enter your name and age:tom 12 34 Hello,tom,your age is 12 34! $ ./test.sh Enter your name and age:tom Hello,tom,your age is !在本例中,read命令一次读入两个变量的值,可以看出:如果用户输入大于两个,则剩余的数据都将被赋值给第二个变量。如果输入小于两个,第二个变量的值为空。
如果在使用read时没有指定变量,则read命令会将接收到的数据放置在环境变量REPLY中:
$ cat test.sh #!/bin/bash echo "\$REPLY=$REPLY" read -p "Enter one number:" echo "\$REPLY=$REPLY" $ ./test.sh $REPLY= Enter one number:12 $REPLY=12默认情况下read命令会一直等待用户输入,使用-t选项可以指定一个计时器,-t选项后跟等待输入的秒数,当计数器停止时,read命令返回一个非0退出状态。
$ cat test.sh #!/bin/bash if read -t 5 -p "Enter your name:" name then echo "Hello $name!" else echo echo "timeout!" fi $ ./test.sh Enter your name:world Hello world! $ ./test.sh Enter your name: timeout!使用-n选项可以设置read命令记录指定个数的输入字符,当输入字符数目达到预定数目时,自动退出,并将输入的数据赋值给变量。
$ cat test.sh #!/bin/bash read -n 1 -p "Enter y(yes) or n(no):" choice echo echo "your choice is : $choice" $ ./test.sh Enter y(yes) or n(no):y your choice is : y运行脚本后,只需输入一个字母,read命令就自动退出,这个字母被传给了变量choice。
使用-s选项,能够使用户的输入不显示在屏幕上,最常用到这个选项的地方就是密码的输入。
$ cat test.sh #!/bin/bash read -s -p "Enter your passwd:" passwd echo echo "your passwd is : $passwd" $ ./test.sh Enter your passwd: your passwd is : 123456read命令还可以读取LInux存储在本地的文件,每调用一次read命令,都会从标准输入中读取一行文本,利用这个特性,我们可以将文件中的内容放到标准输入流中,然后通过管道传递给read命令。
$ cat test.txt apple pen pear banana orange $ cat test.sh #!/bin/bash count=1 cat test.txt | while read line do echo "Line $count: $line" count=$[$count+1] done echo "the file is read over" $ ./test.sh Line 1: apple Line 2: pen Line 3: pear Line 4: banana Line 5: orange the file is read over读到文件末尾,read命令以非零状态码退出,循环结束。
相关文章推荐
- 30分钟玩转Shell-第一个Shell脚本
- Linux下使用Shell脚本实现ftp的自动上传下载的代码小结
- shell 实现后台执行秒级任务
- win10安装系统自带应用
- Linux命令行与Shell脚本编程
- Xshell 免密登陆 linux
- 两步实现在Git Bash中用Sublime打开文件
- shell基础知识总结
- shell awk实战
- Shell中的()和(())
- -bash: xx: command not found 在有yum源情况下处理
- Linux shell编程之使用管道或者重定向循环输出
- shell
- 在shell脚本中添加暂停,按任意键继续
- 【Bash】codeacademy笔记
- 如何定制修改你的bash提示内容?
- crontab任务执行的环境
- shell脚本自动清理备份文件
- powershell 移动OU
- 【Contiki学习】01.Contiki-stm32系统下实现serial-shell功能