目录
1.read命令
命令格式:read 【选项】 【变量名】
子选项: -p “提示信息”: #等待read输入时,输出提示信息。
-t 秒数: #read命令会一直等待用户输入,使用此选项可以指定等待时间。
扫描二维码关注公众号,回复:
13799624 查看本文章
-n 字符数: #read命令只接受指定的字符数量,然后就会执行。
-s #隐藏输入内容,适用于机密信息的输入。
变量名:变量命名可以自定义,如果不指定变量名,会把输入保存入默认变量REPLY如果只提供一个变量名,则整个输入行赋予该变量。如果提供了一个以上的变量名,则输入行分为若干字,一个接一个地赋予各个变量,而命令行上的最后一个变量取得剩余所有字。
2.read命令基本使用
#!/bin/bash
echo -n "Enter your name : "
read name
echo "hello $name ! welcome to BeiJing"
3.read不指定变量
#!/bin/bash
read -p "Enter your name : "
echo
echo "hello $REPLY ! welcome to BeiJing"
4.read 输入超时写法
#!/bin/bash
if read -t 5 -p "Enter your name : "
then
echo "hello $REPLY,welcome to BeiJing"
else
echo "sorry, Output timeout, please execute the command again !"
fi
5.read 隐藏输入
#!/bin/bash
if read -t 5 -p "Enter your name : "
then
echo "hello $REPLY,welcome to BeiJing"
else
echo "sorry, Output timeout, please execute the command again !"
fi
echo "---------"
if read -s -t 5 -p "please enter your password : "
then
echo -n "status : $? , Ok"
else
echo "sorry, Output timeout, please execute the command again !"
fi
6.read命令实例演示
[root@localhost ~]# cat xx.sh #编写一个名为xx.sh的脚本
#!/bin/bash
read -t 30 -p "请输入姓名:" name #等待30秒,提示信息为“姓名..”,赋予变量”name“
read -t 30 -s -p "请输入年龄:" age #等待30秒,隐藏输入内容提示信息为“年龄..”变量age
echo -e "" #输入一个空行,没有的话在当前格式默认不换行。
read -t 30 -n 1 -p "请输入性别:" sex #等待30秒,提示信息为性别..,字符数1,变量sex
echo -e "" #输入一个空行,没有的话在当前格式默认不换行。
echo "$name" #分别输出$name $age $sex
echo "$age"
echo "$sex