read命令接受从标准输入或者另一个文件描述符的输入。下面来看实例。参考自:《shell脚本大全》
#!/bin/bash
echo -n "input your name"
read name
echo "hello $name,welcome
当执行时,输入姓名 michael jack(注意之间有空格),输出很好的显示 hello michael jack,welcome~
当我们想把michael 和 jack 分开,需要制定多个变量
#!/bin/bash
echo -n "input your name"
read first second
echo "hello $second $first,welcome"
~
~
此时你输入michael jack,最后显示的为jack michael
如果不指定变量呢。
n "input your name"
read
echo "hello $REPLY,welcome"
他会存进默认的REPLY变量中。
当使用read命令时,次脚本有可能会一直等待用户的输入。我们可以设置一个定时器,当定时器过期后,read命令返回一个非0的推出状态码
#!/bin/bash
if read -t 3 -p "input name " name
then
echo "name is $name"
else
echo "timeout"
fi
~
有时候需要让自己的输入不再屏幕上显示,可以使用-s
-p "enter you name" name
echo "name is $name"