views:

58

answers:

3

How can I write a simple shell script that will check if someone using display :0? This does not work:

if [ 'who | grep " :0 "' != "" ]
then
    echo "hi"
fi
A: 
#!/bin/sh
R=$(who | grep " :0 ")
echo $R
if [ "$R" != "" ]; then
    echo "hi"
fi
mr.web
This should work also. What's the problem (or are you simply answering your own question)?
BlueRaja - Danny Pflughoeft
i am answering my own question =]
mr.web
A: 
if who | grep " :0 "
then
    echo "hi"
fi

Note that the output of who is different for different versions of who. For the GNU coreutils 7.4 version of who you need grep '(:0' instead of grep " :0 "

Florian Diesch
+1  A: 

Some of the other answers work, but there's no need to capture the output of the grep (using $() or backtics) for a string comparison, because grep's exit status will indicate success or failure. So you can reduce it to this:

if who | grep -q ' :0 '; then
    echo hi
fi

Or even simpler:

who | grep -q ' :0 ' && echo hi

Notes:

  • "if" operates on a command or a pipeline of commands.

  • Left square bracket is actually a command, another name for 'test'.

  • The q option suppresses grep's output (in most versions).

  • Instead of invoking who, grep, and test you can just invoke who and grep.

  • As another answer noted, you may need to grep for something besides ' :0 ' depending on your system.

Rob Davis