read基本用法
~~注:本程序中代码的执行方式也可以通过先给脚本添加执行权限,然后./scriptName来执行
#!/bin/bash
# read基本用法
# -n 用户直接在名字后面输入内容
echo -n "输入您的名字:"
# 将输入的内容保存到name变量中
read name
echo "您好 $name,欢迎来到我的世界!"
[root@localhost scripts]# bash readtest.sh
输入您的名字:TOM
您好 TOM,欢迎来到我的世界!
#!/bin/bash
# -p参数使用
# -p 在命令行直接指定提示符
read -p "请输入你的年龄:" age
days=$[ $age * 365 ]
echo "你已经出生了$days天了"
[root@localhost scripts]# bash readtest1.sh
请输入你的年龄:10
你已经出生了3650天了
#!/bin/bash
#将提示符后输入的所有数据分配给单个变量
read -p "请输入两个数:" a b
echo "两个数的和:$[ $a + $b ]"
[root@localhost scripts]# bash readtest2.sh
请输入两个数:1 2
两个数的和:3
read后不指定变量
#!/bin/bash
# read命令行中不指定变量,如果是这样,read命令会将它收到的任何数据都放进特殊环境变量$REPLY中
read -p "请输入您所在城市:"
echo
echo "我居住在$REPLY,欢迎来到$REPLY"
[root@localhost scripts]# bash readtest3.sh
请输入您所在城市:郑州
我居住在郑州,欢迎来到郑州
-t 指定计时器
#!/bin/bash
#-t指定read命令等待输入的秒数,计时器过期后,会返回一个非0的状态退出码
if read -t 5 -p "请输入您的姓名:" name
then
echo "你好,$name,欢迎来到此脚本"
else
echo
echo "对不起,只有五秒时间哟!!"
fi
[root@localhost scripts]# bash readtest4.sh
请输入您的姓名:中国
你好,中国,欢迎来到此脚本
[root@localhost scripts]# bash readtest4.sh
请输入您的姓名:
对不起,只有五秒时间哟!!
read 通过-n#统计字符数
#!/bin/bash
# 通过-n#指定要输入的数据长度
#-n1表示只能输入一个字符,read命令会接受输入并将它传给变量,无需按回车
read -n1 -p "您确定要继续此操作吗?[Y|N]?" answer
case $answer in
Y | y) echo
echo "很好,继续..." ;;
N | n) echo
echo "好的,再见 "
exit ;;
esac
echo "这里是脚本结尾哟"
[root@localhost scripts]# bash readtest5.sh
您确定要继续此操作吗?[Y|N]?N
好的,再见
[root@localhost scripts]# bash readtest5.sh
您确定要继续此操作吗?[Y|N]?Y
很好,继续...
这里是脚本结尾哟
-s隐藏方式读取
#!/bin/bash
# -s隐藏用户的输入(实际上是数据会被显示,只是read命令会将文本颜色设成与背景色一样)
read -s -p "请输入您的密码:" password
echo
echo "您的密码真的是$password吗"
[root@localhost scripts]# bash readtest6.sh
请输入您的密码:
您的密码真的是123456吗
从文件中读取内容
#1.通过输入重定向的方式将数据传入while循环
#!/bin/bash
#从文件中读取信息
count=1
while read line
do
echo "行 $count:$line"
count=$[ $count +1 ]
done < test
#2.通过管道将数据传递给while循环
#!/bin/bash
#从文件中读取信息
count=1
cat test | while read line
do
echo "行 $count:$line"
count=$[ $count +1 ]
done
#test文件中内容
[root@localhost scripts]# cat test
123
123
456
789
#执行结果
[root@localhost scripts]# bash readtest7.sh
行 1:123
行 2:123
行 3:456
行 4:789