1. 基本的读取
echo -n "Enter your name:"
read name
echo "hello $name"
[-n]:不换行
read -p "Enter your name:" name
echo "hello $name"
[-p]:允许直接在read命令中指定提示符
read -p "Enter your name and age:" name age
echo "i am $age years old ,my name is $name"
read -p "Enter your name:"
echo "hello $REPLY"
如果没有指定变量,会将接收到的任何数据都放到特殊环境变量REPLY中。
2. 读取超时
if read -t 5 -p "Enter your name:"name
then
echo "hello $name"
else
echo "time out"
也可以通过达到预设的字符数后,自动退出
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
Y|y) echo
echo "cotinue...";;
N|n) echo
echo "exit";;
exit
esac
[-n和1]在一起使用,表示接收单个字符后退出
3. 隐藏方式读取
read -s -p "Enter your password:" password
echo "your password is $password"
[-s]可以避免在read命令将输入数据显示在显示器上(实际是会显示的,只是颜色改成和背景色一样了)
4. 从文件中读取
count=1
cat test.txt | while read line
do
echo "line $count:$line"
count =$[ $count + 1 ]
done