Linux Shell基礎 read命令
阿新 • • 發佈:2018-11-21
read命令
read 命令用於接收標準輸入(鍵盤)的輸入,或者其他檔案描述符的輸入。得到輸入後,read 命令將資料放入一個標準變數中,read 命令格式如下:
[[email protected] ~]# read [選項] [變數名]
選項:
- -p "提示資訊":在等待read輸入時,輸出提示資訊;
- -t 秒數:read命令會一直等待使用者輸入,使用此選項可以指定等待時間;
- -n 字元數:read命令只接收指定的字元數就會執行;
- -s: 隱藏輸入的資料,適用於機密資訊的輸入;
- 變數名可以自定義。如果不指定變數名,則會把輸入儲存到預設變數REPLY中;
- 如果只提供了一個變數名,則將整個輸入行賦予該變數;
- 如果提供了一個以上的變數名,則輸入行分為若干字,一個接一個地賦予各個變數,而命令列上的最後一個變數取得剩餘的所有字;
read命令示例
[[email protected] sh]# vi read.sh #!/bin/bash read -t 30 -p "Please input your name:" name #提示"請輸入姓名"並等待30秒,把使用者的輸入儲存到變數name中 echo "Name is $name" #看看變數"$name"中是否儲存了你的輸入 read -s -t 30執行指令碼:-p "Please enter your age:" age #提示"請輸入年齡"並等待30秒,把使用者的輸入儲存到變數age中 #年齡是隱私,所以我們用"-s"選項隱藏輸入 echo -e "n" #調整輸出格式,如果不輸出換行,則一會兒的年齡輸出不會換行 echo "Age is $age" read -n 1 -t 30 -p "Please select your gender[M/F]:" gender #提示"請選擇性別"並等待30秒,把使用者的輸入儲存到變數gender中 #使用"-n 1"選項只接收一個輸入字元就會執行(無須按回車鍵) echo -e "\n" echo"Sex is $gender"
[[email protected] sh]# chmod 755 read.sh 賦予執行許可權 [[email protected] sh]#./read.sh #執行指令碼 Please input your name: zhang san #在read的提示介面輸入姓名 Name is zhang san #"$name"變數中儲存了我們的輸入 Please enter your age: #因為加入了"-s"選項,所以輸入不會顯示在命令列上 Age is 18 #"$age"變數中儲存了我們的輸入 Please select your gender[M/F]: M #因為加入了"-n 1"選項,所以只能輸入一個字元 Sex is M # "$gender"變數中儲存了我們的輸入