BASH- Run MPlayer if either there are no users on display :0 or if there is more than one argument
This is the script I currently have-
#!/bin/bash
if["开发者_运维问答$#" == "2" OR who | grep ":0" == ""]
export DISPLAY=:0
xset dpms force on
mplayer -fs $1.mp4
fi
It doesn't work.
Thanks for your help.
You should spend some time reading man test
, it looks to me like you've got several problems here:
if [ "$#" = "2" -o -z "$(who | grep ':0')" ]; then
- Notice the space after the
[
. - Notice the one equal sign for string compare.
- Notice that
-o
is the OR operator. - Notice the
-z
for testing against the empty string. - Notice the
$(...)
to execute the who command. - Notice the space before the
]
. - However,
who
prints out times andgrep
is going to match a lot of false positives againstHH:MM:SS
. You may want to improve your match. - And as other answers note, you should probably check the success of the
$(who|grep)
, rather than testing for empty string output.
In the future, more detail than "it doesn't work" is preferred ;)
In BASH, the test for NULL is -z
, e.g if [ -z "$NAME" ]; then ...
. However, you can just as easily use the exit status from grep instead:
root@tpost-desktop:/usr/src# who | grep :0
tpost tty7 2010-05-23 09:16 (:0)
root@tpost-desktop:/usr/src# echo $?
0
root@tpost-desktop:/usr/src# who | grep :123
root@tpost-desktop:/usr/src# echo $?
1
If grep did not find what you asked, it will exit with a non-zero status. So you could do something like:
who | grep :0 >/dev/null 2>&1
if [ $? = 0 ]; then
USING_DISPLAY=1
else
USING_DISPLAY=0
fi
Then test the value of USING_DISPLAY
, play the movie if its 0
There needs to be a space after the if
, after the [
and before the ']'.
#!/bin/bash
if [ "$#" == "2" ] || ! who | grep '(.*:0.*)$' > /dev/null 2>&1
then
export DISPLAY=:0
xset dpms force on
mplayer -fs $1.mp4
fi
精彩评论