开发者

Bash scripting - execute and grep command inside script

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

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

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

if [ `who | grep "user0开发者_开发问答00"` ] then things

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


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

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


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. grep exits 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.


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

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


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:

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

If you are using GNU grep, you can use the -s and -q options instead:

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

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜