开发者

What does "who | grep $1" command do in the shell script?

I am learning shell programmin开发者_Python百科g from the very basics using the book called Beginning Linux Programming (4th Edition). I am confused by this script with an until-clause:

#!/bin/bash

until who | grep "$1" > /dev/null
do
   sleep 60
done

# Now ring the bell and announce the unexpected user.

echo -e '\a'
echo "***** $1 has just logged in *****"

exit 0

My quesiton is what is who | grep "$1" > /dev/null used for here? Why redirect the grep output to /dev/null?


The 'until' loop is used to test a condition, as you mentioned, and will run all the 'do|done' block until the condition present becomes true. In other words, it only executes the code block when the condition present is FALSE, and runs it until it becomes true. The script you are testing is useful for catching a logged in user that you pass as a parameter to the script (hence, the grep "$1", being $1 a positional parameter). It will sleep for a minute (sleep 60) until that user logs in to the system, and then it will exit the loop and do all the '$1 has just logged in' stuff. The redirection of grep output to /dev/null is used to not display the output of the grep comand (you could have used grep -q "$1" and that will achieve the same effect).

Hope to have clarified your doubts.


while and until (and, admittedly, if) look at the exit code of the test, not at any text that may or may not be generated on stdout (or stderr).

I suspect the reason redirection to /dev/null has been used is because the command only generates output if there is a match, most of the time there is (admittedly) none, but when there is, you're not interested in seeing the result.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜