Bash -eq评估为true?

Ton*_*ony 1 bash loops

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

码:

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"
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

tri*_*eee 5

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

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

if grep -Eq "$user" /etc/passwd; then
    ...
Run Code Online (Sandbox Code Playgroud)

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