Bash -eq评估为true?

时间:2014-06-27 14:50:32

标签: bash loops

有人可以帮我弄清楚为什么我的代码会产生下面的输出?特别是当/ etc /传递中没有匹配的字符串?

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"

输出:

+ 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

1 个答案:

答案 0 :(得分:5)

您正在检查echo的退出代码,这始终是成功的。

无论如何,这样做的惯用方法是

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

通常,您几乎不需要明确地检查$?

相关问题