如何检查grep是否没有输出? [英] How to check if grep has no output?

查看:141
本文介绍了如何检查grep是否没有输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我需要检查收件人用户名是否位于/ etc / passwd中,该用户名包含我班的所有用户,但我尝试了if语句和grep的几种不同组合,但都没有成功。我能想到的最好的是,但我认为它不能正常工作。
我的逻辑是,如果grep为空,则用户无效。

  send_email()
{
message =
address =
attachment =
validuser = 1
until [$ validuser=0]
do
echo输入电子邮件地址:
读取地址
如果[-z grep $地址/ etc / passwd]
然后
validuser = 0
else $ b $ b validuser = 1
fi
echo -n输入消息主题:
读取消息
echo
echo输入文件想要附上:
阅读附件
邮件-s$ message$ address<$ attachment
完成
press_enter
}


解决方案

使用getent并检查grep的退出代码。避免使用/ etc / passwd。相当于shell:

 > getent passwd | grep -q valid_user 
> echo $?
0

> getent passwd | grep -q invalid_user
> echo $?
1


So I need to check if the recipient username is in /etc/passwd which contains all the users in my class, but I have tried a few different combinations of if statements and grep with no success. The best I could come up with is below, but I don't think it's working properly. My logic behind it is that if the grep is null, the user is invalid.

send_email()
{
  message=
  address=
  attachment=
  validuser=1
  until [ "$validuser" = "0" ]
    do
    echo "Enter the email address: "
    read address
    if [ -z grep $address /etc/passwd ]
      then
    validuser=0
    else
        validuser=1
    fi
    echo -n "Enter the subject of the message: "
    read message
    echo ""
    echo "Enter the file you want to attach: "
    read attachment
    mail -s "$message" "$address"<"$attachment"
    done
    press_enter 
}

解决方案

Use getent and check for grep's exit code. Avoid using /etc/passwd. Equivalent in the shell:

> getent passwd | grep -q valid_user
> echo $?
0

> getent passwd | grep -q invalid_user
> echo $?
1

这篇关于如何检查grep是否没有输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆