![[shell基础]——read命令 [shell基础]——read命令](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
read命令:在shell中主要用于读取输入、变量、文本
1. 接受标准输入(键盘)的输入,并将输入的数据赋值给设置的变量
【按回车键——表示输入完毕】
【若输入的数据多于设置的变量数,则将多出的部分全部赋给最后一个变量】
【若没有设置变量,则将输入的数据赋给环境变量REPLAY】
#!/bin/bash
echo -n "Enter your name:"
read name1 name2
echo hello,$name1,$name2 # ./read.sh
Enter your name:taeyeon jessica
hello,taeyeon,jessica
2. -p 在read命令行中直接print一个提示
#!/bin/bash
read -p "Enter your name:" name1 name2
echo hello,$name1,$name2 # ./read.sh
Enter your name:taeyeon jessica
hello,taeyeon,jessica
3. -t 实现计时输入。指定read命令等待输入的秒数。
#!/bin/bash
if read -t -p "Enter your name:" name ## -p后要直接接提示语,注意多选项时怎么用
then
echo hello,$name
else
echo -e "\nsorry,too slow"
fi
exit # ./read.sh
Enter your name:jelly
hello,jelly
# ./read.sh
Enter your name:
sorry,too slow
4. -n 实现计数输入。指定read命令接受输入的数据长度。当超过这个长度,无论按任意键都表示输入结束。
-n1 表示接受一个字符的输入就退出,不需要按回车键
#!/bin/bash
read -n1 -p "Do you want to continue [y/n]?" y1
case $y1 in
Y|y) echo -e "\nok,continue!";;
N|n) echo -e "\nok,stop!";;
*) echo -e "\nerror choice!"
esac # ./read.sh
Do you want to continue [y/n]?y
ok,continue!
# ./read.sh
Do you want to continue [y/n]?n
ok,stop!
# ./read.sh
Do you want to continue [y/n]?p
error choice!
5. -s 实现隐藏输入。实际是使得输入的数据和背景色一致。常用于接受密码输入时。
#!/bin/bash
read -s -p "Enter you password:" passwd
echo -e "\n"
echo "haha,your passwd is:$passwd" [root@sxjy ~]# ./read.sh
Enter you password:
#看不见吧...
haha,your passwd is:aixocm
6. 读取文本中的数据作为read的输入
#!/bin/bash
count=
cat gg.txt | while read name #逐行读取gg.txt文本中的内容给变量name
do
echo "$count:$name"
count=$[$count+]
done # ./read.sh
:taeyeon
:jessica
:sunny