BASH- Run MPlayer if either there are no users on display :0 or if there is more than one argument

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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.

回答1:

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 and grep is going to match a lot of false positives against HH: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 ;)



回答2:

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



回答3:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!