开发者

sh shell code - retrieving command result

开发者 https://www.devze.com 2023-01-01 06:57 出处:网络
How can I write a simple shell script that will check if someone using display :0?This does not work:

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


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.


#!/bin/sh
R=$(who | grep " :0 ")
echo $R
if [ "$R" != "" ]; then
    echo "hi"
fi


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 "

0

精彩评论

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