2

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.

2
  • 1
    Try making it work without osascript first Commented Mar 3, 2015 at 19:16
  • @thatotherguy’s advice is also good: first, make the ps line work on the command line; only when you understand that, should you slot it into the if statement. Commented Mar 3, 2015 at 19:35

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Easier than grep "Skype" | grep -v "grep" is to use regex to miss the grep: grep "[S]kype". This will match any 'S' next to a 'k', but not the square brackets in the grep statement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.