read 是 Shell 取得使用者輸入最方便的方式。
read -p "Prompt" variable1 variable2 variableN
-p "Prompt" 會顯示提示訊息並與輸入停留在同一行;輸入的多個值會依序指派給後面的變數,多餘的值全給最後一個變數。
#!/bin/bash read -p "Enter your name : " name echo "Hi, $name. Let us be friends!"
存檔後執行:
chmod +x greet.sh ./greet.sh Enter your name : Tomcat Hi, Tomcat. Let us be friends!
#!/bin/bash read -p "Enter the Internet domain name (e.g. nixcraft.com) : " domain_name whois $domain_name
避免腳本被卡住,可以限制輸入時間,超過秒數就繼續往下跑:
#!/bin/bash read -t 10 -p "Enter the Internet domain name (e.g. nixcraft.com) : " domain_name whois $domain_name
讀取密碼時用 -s,輸入的內容不會回顯在螢幕上:
#!/bin/bash read -s -p "Enter Password : " my_password echo echo "Your password - $my_password"
注意 echo 那兩個空行是為了在隱藏輸入後換行,讓後續輸出不要黏在提示訊息後面。另外若要一次讀入整行含空白的內容,建議寫成 read -r line,-r 可避免反斜線被當成跳脫字元,是腳本中值得養成的習慣。