0

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
5
  • What is the question? What is the processor arch? What is the OS?
    – Aryabhatta
    Commented May 26, 2010 at 13:40
  • @Moron: This is an sh (bash?) script, so the OS is unix. Commented May 26, 2010 at 13:59
  • @BlueRaja: The title said ShellCode, which I presumed was the assembly opcode bytes and so exact OS and processor architecture would matter. The title has been edited now, I see.
    – Aryabhatta
    Commented May 26, 2010 at 14:20
  • I guess we can let my close vote decay then. Sorry for the confusion mr.web.
    – Aryabhatta
    Commented May 26, 2010 at 14:25

3 Answers 3

2

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.

0
#!/bin/sh
R=$(who | grep " :0 ")
echo $R
if [ "$R" != "" ]; then
    echo "hi"
fi
2
  • This should work also. What's the problem (or are you simply answering your own question)? Commented May 26, 2010 at 14:42
  • 1
    i am answering my own question =]
    – mr.web
    Commented May 26, 2010 at 15:22
0
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 "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.