bash 如何检查grep是否没有输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27392410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if grep has no output?
提问by Duncan
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.
所以我需要检查接收者的用户名是否在包含我班级所有用户的 /etc/passwd 中,但我尝试了几种不同的 if 语句和 grep 组合,但没有成功。我能想到的最好的方法如下,但我认为它不能正常工作。我背后的逻辑是,如果 grep 为空,则用户无效。
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
}
回答by Marcellus
Just do a simple if like this:
如果像这样,只需做一个简单的:
if grep -q $address /etc/passwd
then
echo "OK";
else
echo "NOT OK";
fi
The -q option is used here just to make grep quiet(don't output...)
此处使用 -q 选项只是为了使 grep安静(不要输出...)
回答by helloV
Use getent and check for grep's exit code. Avoid using /etc/passwd. Equivalent in the shell:
使用 getent 并检查 grep 的退出代码。避免使用 /etc/passwd。在外壳中等效:
> getent passwd | grep -q valid_user
> echo $?
0
> getent passwd | grep -q invalid_user
> echo $?
1
回答by repzero
Your piece of code
你的一段代码
if [ -z grep $address /etc/passwd ]
You haven't save the results of grep $address /etc/passwd
in a variable. before putting it in the if statement and then testing the variable to see if it is empty.
您尚未将 的结果保存grep $address /etc/passwd
在变量中。在将它放入 if 语句之前,然后测试变量以查看它是否为空。
You can try it like this
你可以这样试试
check_address=`grep $address /etc/passwd`
if [ -z "$check_address" ]
then
validuser=0
else
validuser=1
fi
回答by alienchow
The -z check is for variable strings, which your grep isn't giving. To give a value from your grep command, enclose it in $():
-z 检查用于变量字符串,您的 grep 没有提供。要从您的 grep 命令中给出一个值,请将其括在 $() 中:
if [ -z $(grep $address /etc/passwd) ]
回答by antigenius
easiest one will be this
最简单的就是这个
$ cat test123
12345678
$ cat test123 | grep 123 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
grep result exist
$ cat test123 | grep 999 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
grep result doesn't exist