Linux shell编程之read 命令

    xiaoxiao2021-03-26  22

    read命令接受用户输入,并将输入放入一个标准变量中。

    基本用法如下:

    $ 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命令以非零状态码退出,循环结束。

    转载请注明原文地址: https://ju.6miu.com/read-660782.html

    最新回复(0)