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 ()
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."
fielse
echo "the string '$reply' is not a valid filename."
fi
Python讀取鍵盤輸入
python提供了兩個內建函式從標準輸入讀入一行文字,預設的標準輸入是鍵盤。如下 raw input 函式從標準輸入讀取乙個行,並返回乙個字串 去掉結尾的換行符 str raw input enter your input print received input is str 這將提示你輸入任意字...
Python 讀取鍵盤輸入字元
找了一圈,發現python下讀取鍵盤輸入的字元還挺麻煩的,找到這個例子,linux下用這個,ch是讀取的字元 import os import sys import tty,termios fd sys.stdin.fileno old settings termios.tcgetattr fd t...
shell接受鍵盤輸入引數
root localhost read 選項 變數名 選項 a 後跟乙個變數,該變數會被認為是個陣列,然後給其賦值,預設是以空格為分割符。p 提示資訊 在等待read輸入時,輸出提示資訊 t 秒數 read命令會一直等待使用者輸入,使用此選項可以指定等待時間 n 數字 read命令只接受指定的字元數...