2014-06-27 63 views
1

有人可以幫我弄清楚爲什麼我的代碼在下面的結果輸出結果?特別是當/ etc /中的字符串沒有匹配時傳遞?Bash -eq的計算結果爲true?

CODE:

for user in ${usernames[*]} 
do 
egrep ${user} /etc/passwd >/dev/null 
echo -e "\nChecking if users already exist..." 
if [ $? -eq 0 ]; then 
echo -e "${user} exists!, skipping creation" 

OUTPUT:

+ for user in '${usernames[*]}' 
+ egrep addaf /etc/passwd 
+ echo -e '\nChecking if users already exist...' 
Checking if users already exist... 
+ '[' 0 -eq 0 ']' 
+ echo -e 'addaf exists!, skipping creation' 
addaf exists!, skipping creation 

回答

5

正在檢查從echo退出代碼,這始終是一個成功。

反正慣用的方式做到這一點是

if grep -Eq "$user" /etc/passwd; then 
    ... 

一般來說,你應該幾乎從來沒有需要檢查$?明確。

+0

啊SOB! - 謝謝 – Tony