2012-08-09 111 views
8

我試圖以另一個用戶的身份運行命令並以該用戶的身份讀取輸入。由於某些原因,腳本不會在read命令中暫停,我不確定原因。下面是腳本的例子:Bash腳本不等待閱讀

#!/bin/bash 
username='anthony' 
sudo -H -u "$username" bash << 'END_COMMAND' 

# Commands to be run as new user 
# ------------------------------- 

echo "#! Running as new user $USER..." 


echo "#! Gathering setup information for $USER..." 
echo -n "Enter your name and press [ENTER]: " 
read name 
echo -n "Enter your email and press [ENTER]: " 
read email 
END_COMMAND 

echo "Done" 

任何想法,這是爲什麼不停止在read nameread email

回答

20

read正在從stdin讀取,bash正在從hedooc繼承其來自sudo的stdin。如果你想讓它來自其他地方,你需要明確。例如:

bash 3<&0 << 'END_COMMAND' 
... 
read <&3 
... 

這不適用於sudo,但是,因爲sudo關閉了非標準的文件描述符。但須藤不關閉標準錯誤,所以如果你能擺脫重複使用的文件描述符,你可能能夠做到:

sudo -H -u "$username" bash 2<&0 << 'END_COMMAND' 
... 
read -u 2 email 
... 

但它可能是更安全的事:

sudo -H -u "$username" bash << 'END_COMMAND' 
... 
read email < /dev/tty 
... 
+0

很好的答案,謝謝。 – alukach 2012-08-09 22:36:20

0

你能讓這個腳本檢查它是否以sudo方式運行,如果不是,使用sudo執行它本身?

#!/bin/bash 
username='anthony' 

if [[ -z "${SUDO_USER}" ]]; then 
    exec sudo -H -u "${username}" -- $0 
fi 

echo " 
# Commands to be run as new user 
# ------------------------------- 
" 
echo "#! Running as new user $USER..." 

echo "#! Gathering setup information for $USER..." 
echo -n "Enter your name and press [ENTER]: " 
read name 
echo -n "Enter your email and press [ENTER]: " 
read email