讀取鍵盤輸入
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