我創建了以下bash腳本,從用戶獲得口令完美的作品:BASH - 函數來獲取用戶密碼
while [ -z "$PASSWORD" ]
do
echo "Please enter a password:"
read -s PASSWORD1
echo "Please re-enter the password to confirm:"
read -s PASSWORD2
if [ "$PASSWORD1" = "$PASSWORD2" ]; then
PASSWORD=$PASSWORD1
else
# Output error message in red
red='\033[0;31m'
NC='\033[0m' # No Color
echo ""
echo -e "${red}Passwords did not match!${NC}"
fi
done
# This is just here to prove script works
echo "password is: $PASSWORD"
但是,如果我把它放在一個功能,它停止工作:
function getPasswordFromUser()
{
while [ -z "$PASSWORD" ]
do
echo "Please enter a password:"
read -s PASSWORD1
echo "Please re-enter the password to confirm:"
read -s PASSWORD2
if [ "$PASSWORD1" = "$PASSWORD2" ]; then
PASSWORD=$PASSWORD1
else
# Output error message in red
red='\033[0;31m'
NC='\033[0m' # No Color
echo ""
echo -e "${red}Passwords did not match!${NC}"
fi
done
echo $PASSWORD
}
PASSWORD=$(getPasswordFromUser)
# This is just here to check if script worked
echo "got password $PASSWORD"
如果我改變從PASSWORD=$(getPasswordFromUser)
向函數調用:getPasswordFromUser;
那麼該方法開始「工作」,但密碼是輸出到屏幕上,我還沒有捕捉到它。
有沒有一種方法來更新這個bash腳本,這樣我可以調用一個函數來從用戶那裏獲取密碼而沒有被顯示在終端密碼?
- 萬一它很重要,這是Debian/Ubuntu。
謝謝!關鍵是:「在bash中沒有範圍,所以一旦函數執行完畢就可以訪問它,所以我可以運行'getPasswordFromUser;'並且'PASSWORD'將被設置在函數之外。不需要在該函數內部回顯密碼並嘗試捕獲它。 – Programster 2014-12-03 13:55:00