一、获取用户输入
1、基本读取read命令接收标准输入的输入,或其它文件描述符的输入。得到输入后,read命令将数据输入放入一个标准变量中。[root@rac2 ~]# cat t8.sh #!/bin/bash#testing the read commandecho -n "enter your name:" ---:-n用于允许用户在字符串后面立即输入数据,而不是在下一行输入。read nameecho "hello $name ,welcome to my program."[root@rac2 ~]# ./t8.sh enter your name:zhouhello zhou ,welcome to my program.read命令的-p选项,允许在read命令行中直接指定一个提示:[root@rac2 ~]# cat t9.sh #!/bin/bash#testing the read -p optionread -p "please enter your age:" age ---age与前面必须有空格echo "your age is $age"[root@rac2 ~]# ./t9.sh please enter your age:10your age is 102、在read命令中也可以不指定变量,如果不指定变量,那么read命令会将接收到的数据防止在环境变量REPLAY中[root@rac2 ~]# cat t10.sh #!/bin/bash#tesing the replay environment variableread -p "enter a number:"factorial=1for (( count=1; count<=$REPLY; count++ )) do factorial=$[ $factorial * $count ]doneecho "the factorial of $REPLY is $factorial"[root@rac2 ~]# ./t10.sh enter a number:5the factorial of 5 is 1203、计时-t选项指定read命令等待输入的秒数。当计时器计时数满时,read命令返回一个非零退出状态[root@rac2 ~]# cat t11.sh #!/bin/bash#timing the data entryif read -t 5 -p "please enter your name:" namethen echo "hello $name ,welcome to my script"else echo "sorry ,tow slow!"fi[root@rac2 ~]# ./t11.sh please enter your name:zhouhello zhou ,welcome to my script[root@rac2 ~]# ./t11.sh please enter your name:sorry ,tow slow!4、默读有时候需要脚本用户进行输入,但不希望输入的数据显示在监视器上,(实际上是显示的只是read命令将文本颜色设置为与背景相同的了)。[root@rac2 ~]# cat t12.sh #!/bin/bash#hiding input data from the monitorread -s -p "enter your password:" passecho "is your password really $pass?"[root@rac2 ~]# ./t12.sh enter your password:is your password really 12345?5、读取文件每调用一次read命令都会读取文件中的一行文本,当文件中没有可读的行时,read命令将以非零退出状态退出。[root@rac2 ~]# cat t13.sh #!/bin/bashcount=1cat test | while read linedo echo "line $count:$line" count=$[$count + 1]done[root@rac2 ~]# ./t13.sh line 1:zhouline 2:xiaoline 3:zhou