Search code examples
bashapplescriptosascript

Check if app is running via bash in shell script


My "if" statement which is responsible for checking if app is running doesn't work. It's always returns "false" Here is a script.sh:

#!/bin/bash
    osascript -e "do shell script \"

        if (ps aux | grep "[[S]kype]" > /dev/null)
        then
            echo "RUNNING" > /Users/someuser/Desktop/RUNNING.txt
        else
            echo "STOPPED" > /Users/someuser/Desktop/STOPPED.txt
        fi

    \" with administrator privileges"

As result script creates "STOPPED.txt" even if application is launched.

How to solve the following problem?

Please note that I can change only "IF" statement.


Solution

  • There are a couple of problems here. You don’t specify it in your post, but you appear to be looking specifically for the app “Skype”. The square brackets, however, have special meaning in grep: they mean any of the enclosed characters. But, by nesting the square brackets, you’re basically ensuring that it won’t match anything. (See Grep ambiguity nested square bracket elsewhere.)

    This is why it is always reporting “stopped”, because nothing is matching.

    You probably want something more like:

    ps aux | grep "Skype"
    

    However, if you run this you will find that, instead, it reports as always running. That’s because this will in fact match the grep itself, as the grep process also contains the desired text. To fix that problem, you’ll need to somehow remove the grep process from the list of matches. (This may have been what your square brackets were for; see the comments.) One way is to use grep -v to exclude lines that match:

    ps aux | grep "Skype" | grep -v "grep"
    

    This should do what you want. I tested it with a simplified form of your script and it correctly reported whether the named app was running or not running:

    #!/bin/bash
    osascript -e "do shell script \"
    
      if (ps aux | grep Skype | grep -v grep > /dev/null)
      then
          echo RUNNING
      else
          echo STOPPED
      fi
    
    \""
    

    Note that while I simplified the rest of your script to make it easier to test, the important change is only in the if statement.

    (Note also that since your searches do not contain spaces, the quotes around the searches are superfluous; you can improve readability by removing them. It doesn’t hurt the script to have them, however.)