read 读取控制台输入
1. 基本语法
read (选项) (参数)
①选项:
-p:指定读取值时的提示符;
-t:指定读取值时等待的时间(秒)如果-t 不加表示一直等待 ②参数
变量:指定读取值的变量名
sh
[root@hadoop100 shell_learn]# cat read_name.sh
#!/bin/bash
read -t 6 -p '请在6s内输入你的名字:' name
if [ $name ]
then
echo "欢迎,$name"
else
echo "用户没有输入名字!程序结束"
fi
[root@hadoop100 shell_learn]# ./read_name.sh
请在6s内输入你的名字:jack
欢迎,jack
[root@hadoop100 shell_learn]# ./read_name.sh
请在6s内输入你的名字:用户没有输入名字!程序结束
2. IFS变量
read命令读取的值,默认是以空格分隔。可以通过自定义环境变量IFS(内部字段分隔符,Internal Field Separator 的缩写),修改分隔标志。
sh
#!/bin/bash
# IFS设为冒号,然后用来分解/etc/passwd文件的一行。
FILE=/etc/passwd
read -p "Enter a username > " user_name
file_info="$(grep "^$user_name:" $FILE)"
if [ -n "$file_info" ]; then
IFS=":" read user pw uid gid name home shell <<< "$file_info"
echo "User = '$user'"
echo "UID = '$uid'"
echo "GID = '$gid'"
echo "Full Name = '$name'"
echo "Home Dir. = '$home'"
echo "Shell = '$shell'"
else
echo "No such user '$user_name'" >&2
exit 1
fi