@@@ read命令
read命令可以把你输入的字符放进一个变量,供你的shell脚本使用。
简单例子:
cat read001.sh ###脚本内容
#!/bin/bash
echo "Enter your name please:"
read name ###会将你输入的字符存入$name变量中
echo "Hellow $name."
# ./read001.sh ###执行脚本
Enter your name please:
###按下回车后,此行第一个光标闪烁
# ./read001.sh
Enter your name please:
Suiryuin ###输入your name
Hellow Suiryuin.
&&& read命令后面也可以定义多个变量
cat read002.sh
#!/bin/bash
echo "Please enter your name!"
read -p "Name:" name1 name2 ###用空格分开了两个变量name1和name2
echo "My name is $name1,My son's name is $name2!"
# ./read002.sh
Please enter your name!
Name:father son
My name is father,My son's name is son! ###成功识别
# ./read002.sh
Please enter your name!
Name:father son1 son2
My name is father,My son's name is son1 son2! ###当你输入的数据值个数超过变量个数时,剩下
的就会全部分配给最后一个变量。
# ./read002.sh
Please enter your name!
Name:"father1 father2" son
My name is "father1,My son's name is father2" son! ###需要注意的是加了"号也不能识别
&&& read命令提供了 -p -s -n -t 等选项,你可以选择你需要的选项自由取用
# cat read003.sh
#!/bin/bash
if read -n 1 -t 5 -s -p "Enter:" num ### -n选项控制你最多驶入的字符数
then -t选项控制可输入的时间,单位为秒
case $num in -p选项可以让你在""内容的后面直接进行输入
y | Y) -s选项可以隐藏你的输入内容,就像输入密码
echo 那样,无法看见
echo "I like $num becouse YYY";;
n | N)
echo
echo "I like $num becouse NNN";;
*)
echo
echo "Please enter yYnN.";;
esac
else
echo
echo "your are so late that this script is over."
fi
# ./read003.sh
Enter: ###输入n或N后直接显示了下行的内容无需按下Enter键
I like n becouse NNN
# ./read003
Enter: ###超过设置的5秒时间不输入,自动显示下一行内容。
your are so late that this script is over.
###超时,read命令就会以非0退出状态码退出,可以使用
这个特性结合如if-then语句或while循环语句,来解
决一些具体情况
&&& read命令可以从文件中逐行读取内容
cat read004.sh
#!/bin/bash
hang=1 ###通过cat命令逐行读取read001.sh内容
cat /root/Desktop/shellscrpit/read001 | while read neirong ###存入neirong变量中
do
echo "NO $hang"
echo "$neirong"
hang=$[ $hang + 1 ]
done
./read004 ###逐行显示read001.sh内容
NO 1
#!/bin/bash
NO 2
echo "Enter your name please:"
NO 3
read name
NO 4
echo "Hellow $name."
以上就是read命令的学习内容,个人觉得学起来比较容易理解,脚本结果也很直观。