读取键盘输入
READ 命令
read 命令基本用法
#! /bin/bash
# 读取多个输入
echo "Enter some values>"
read value1 value2 value3
echo "value1 : $value1"
echo "value2 : $value2"
echo "value3 : $value3"
输入:a b c d e f
输出:
value1 : a
value2 : b
value3 : c d e f // 输入的多余参数会被最后一个读取变量全部接收。
$REPLY 变量: 会接收所有输入。
#! /bin/bash
# $REPLY 读取所有输入
echo "Enter some values>"
read
echo "\$REPLY : $REPLY"
输出:a b c d e f
输出:$REPLY : a b c d e f
read参数:
举例1:读取提示
#!/bin/bash
# read-single: read multiple values into default variable
read -p "Enter one or more values > "
echo "REPLY = '$REPLY'"
举例2:限时读取密码
#!/bin/bash
# read-secret: input a secret pass phrase
if read -t 10 -sp "Enter secret pass phrase > " secret_pass; then
echo -e "\nSecret pass phrase = '$secret_pass'"
else
echo -e "\nInput timed out" >&2
exit 1
if
IFS:读取的数据分割符
含义:SHELL中read 按照变量IFS(内部字符分隔符)区分输入的各个字符。默认IFS值包含一个空格,一个tab和一个换行符,每一个都会把字符串分开。
举例:修改IFS以:区分,并读取/ect/passwd内容,然后展示。
#!/bin/bash
# read-ifs: read fields from a file
FILE=/etc/passwd
read -p "Enter a user name > " user_name
file_info=$(grep "^$user_name:" $FILE) # 读取到输入用户名相关的passwd行。
if [ -n "$file_info" ]; then # 检测匹配到的字符串行存在,且长度大于0。
# 先设置分割符为:然后依次读取并赋值,注意<<< 是Here字符串,在shell中不能用管道。
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
校正输入:
#!/bin/bash
# read-validate: validate input
invalid_input () {
echo "Invalid input '$REPLY'" >&2
exit 1
}
read -p "Enter a single item > "
# input is empty (invalid)
[[ -z $REPLY ]] && invalid_input
# input is multiple items (invalid)
(( $(echo $REPLY | wc -w) > 1 )) && invalid_input
# is input a valid filename?
if [[ $REPLY =~ ^[-[:alnum:]\._]+$ ]]; then
echo "'$REPLY' is a valid filename."
if [[ -e $REPLY ]]; then
echo "And file '$REPLY' exists."
else
echo "However, file '$REPLY' does not exist."
fi
# is input a floating point number?
if [[ $REPLY =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
else
echo "'$REPLY' is not a floating point number."
fi
# is input an integer?
if [[ $REPLY =~ ^-?[[:digit:]]+$ ]]; then
echo "'$REPLY' is an integer."
else
echo "'$REPLY' is not an integer."
fi
else
echo "The string '$REPLY' is not a valid filename."
fi