Bash 脚本 - 在脚本中执行和 grep 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1638503/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:19:31  来源:igfitidea点击:

Bash scripting - execute and grep command inside script

bash

提问by geord

Okay, so I'm learning Bash, and there's that exercise;

好的,所以我正在学习 Bash,还有那个练习;

"Write a script that checks every ten seconds if the user 'user000' is logged in."

“编写一个脚本,每 10 秒检查一次用户 'user000' 是否已登录。”

My idea is to grepa who, but I don't know how to incorporate this into a script. I tried things like

我的想法是grepa who,但我不知道如何将其合并到脚本中。我试过这样的事情

if [ `who | grep "user000"` ] then things

but it returns the matched lines with grep, not true/false.

但它用grep 返回匹配的行,而不是真/假。

回答by chaos

You want grep -q. That's "quiet mode"; just sets status based on whether there were any matches, doesn't output anything. So:

你要grep -q。那是“安静模式”;只是根据是否有任何匹配来设置状态,不输出任何内容。所以:

if who | grep -q "user000"; then things; fi

回答by DVK

You can do

你可以做

who | grep "user000" > /dev/null  2>&1
# You can use "-q" option of grep instead of redirecting to /dev/null 
# if your grep support it. Mine does not.
if [ "$?" -eq "0" ]
then ...

This uses $? - a Shell variable which stores the return/exit code of the last command that was exected. grepexits with return code "0" on success and non-zero on failure (e.g. no lines found returns "1" ) - a typical arrangement for a Unix command, by the way.

这使用 $? - 一个 Shell 变量,用于存储执行的最后一个命令的返回/退出代码。grep成功退出时返回代码“0”,失败时返回非零(例如,找不到行返回“1”)——顺便说一下,这是 Unix 命令的典型安排。

回答by Paused until further notice.

If you're testing the exit code of a pipe or command in a ifor while, you can leave off the square brackets and backticks (you should use $()instead of backticks anyway):

如果你在一个测试管或命令的退出代码if或者while,可以去掉方括号和反引号(你应该使用$()反正不是反引号的):

if who | grep "user000" > /dev/null 2>&1
then
  things-to-do
fi

回答by Walter Mundt

Most answers have the right idea, but really you want to drop all output from grep, including errors. Also, a semicolon is required after the ] for an if:

大多数答案都有正确的想法,但实际上您想删除 grep 的所有输出,包括错误。此外,if 的 ] 后面需要一个分号:

if who | grep 'user000' >/dev/null 2>&1; then
    do things
fi

If you are using GNU grep, you can use the -sand -qoptions instead:

如果您使用的是 GNU grep,则可以使用-s-q选项:

if who | grep -sq 'user000'; then
    do things
fi

EDIT: dropped brackets; if only needs brackets for comparison ops

编辑:删除括号;如果只需要括号进行比较操作

回答by the_mandrill

It's probably not the most elegant incantation, but I tend to use:

这可能不是最优雅的咒语,但我倾向于使用:

if [ `who | grep "user000" | wc -l` = "1" ]; then ....