Linux shell read指令学习

来源:互联网 发布:淘宝店铺首页广告词 编辑:程序博客网 时间:2024/05/16 13:52

linux read 命令

read -p(提示语句)-n(字符个数) -t(等待时间) -s(不回显)

#!/bin/bash
echo -n "Enter your name:"  //参数-n的作用是不换行,echo默认是换行
read name                  //从键盘输入
echo "hello $name,welcome to myprogram"    //显示信息
exit0                      //退出shell程序。

由于read命令提供了-p参数,允许在read命令行中直接指定一个提示。
所以上面的脚本可以简写成下面的脚本::
#!/bin/bash
read -p "Enter your name:" name
echo "hello $name, welcome to my program"
exit 0
在上面read后面的变量只有name一个,也可以有多个,这时如果输入多个数据,则第一个数据给第一个变量,第二个数据给第二个变量,如果输入数据个数过多,则最后所有的值都给第一个变量。如果太少输入不会结束。

在read命令行中也可以不指定变量.如果不指定变量,那么read命令会将接收到的数据放置在环境变量REPLY中。
例如::
read -p "Enter a number"

2、计时输入.
使用read命令存在着潜在危险。脚本很可能会停下来一直等待用户的输入。如果无论是否输入数据脚本都必须继续执行,那么可以使用-t选项指定一个计时器。
-t选项指定read命令等待输入的秒数。当计时满时,read命令返回一个零退出状态;
#!/bin/bash
if read -t 5 -p "please enter your name:" name
then
   echo "hello$name ,welcome to my script"
else
   echo"sorry,too slow"
fi
exit 0

除了输入时间计时,还可以设置read命令计数输入的字符。当输入的字符数目达到预定数目时,自动退出,并将输入的数据赋值给变量。
#!/bin/bash
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
Y | y)
     echo "fine ,continue";;
N | n)
     echo "ok,good bye";;
*)
    echo "error choice";;
esac
exit 0

-s选项能够使read命令中输入的数据不显示在监视器上(实际上,数据是显示的,只是read命令将文本颜色设置成与背景相同的颜色)。
#!/bin/bash
read -s -p "Enter yourpassword:" pass
echo "your password is $pass"
exit 0


每次调用read命令都会读取文件中的"一行"文本。当文件没有可读的行时,read命令将以零状态退出。
读取文件的关键是如何将文本中的数据传送给read命令。
最常用的方法是对文件使用cat命令并通过管道将结果直接传送给包含read命令的while命令
例子::
#!/bin/bash
count=1   //赋值语句,不加空格
cat test | while read line       //cat 命令的输出作为read命令的输入,read读到的值放在line中
do
  echo "Line $count:$line"
  count=$[ $count +1 ]          //注意中括号中的空格。
done
echo "finish"
exit 0
0 0
原创粉丝点击