4

I am new to bash scripting and want to write a short script, that checks if a certain program is running. If it runs, the script should bring the window to the foreground, if it does not run, the script should start it.

#!/bin/bash

if [ "$(wmctrl -l | grep Wunderlist)" = ""]; then
    /opt/google/chrome/google-chrome --profile-directory=Default --app-id=ojcflmmmcfpacggndoaaflkmcoblhnbh
else
    wmctrl -a Wunderlist
fi

My comparison is wrong, but I am not even sure what I should google to find a solution. My idea is, that the "$(wmctrl -l | grep Wunderlist)" will return an empty string, if the window does not exist. I get this error when I run the script:

~/bin » sh handle_wunderlist.sh                                       
handle_wunderlist.sh: 3: [: =: argument expected
1
  • 1
    shellcheck.net would have caught your syntax error; don't execute Bash scripts with sh, because sh isn't (always) Bash. Commented Jul 24, 2016 at 21:50

2 Answers 2

4

You need a space before the closing argument, ], of the [ (test) command:

if [ "$(wmctrl -l | grep Wunderlist)" = "" ]; then
    ....
else
    ....
fi

As a side note, you have used the shebang as bash but running the script using sh (presumably dash, from the error message).

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

3 Comments

A missing whitespace... Thank you, that solved the problem
++ for explaining the syntax problem and pointing out that Bash scripts shouldn't be executed with sh; taking a step back to look at the bigger picture: John1024's approach is the best choice.
The script itself is POSIX-compliant, so it's fine to run with sh. (The shebang is only relevant if running the script itself as a command. #!/bin/sh would be sufficient if that were the case.)
3

Replace:

if [ "$(wmctrl -l | grep Wunderlist)" = ""]; then

With:

if ! wmctrl -l | grep -q Wunderlist; then 

grep sets its exit condition to true (0) is a match was found and false (1) if it wasn't. Because you want the inverse of that, we placed ! at the beginning of the command to invert the exit code.

Normally, grep will send the matching text to standard out. We don't want that text, we just want to know if there was a match or not. Consequently, we added the -q option to make grep quiet.

Example

To illustrate the use of grep -q in an if statement:

$ if ! echo Wunderlist | grep -q Wunderlist; then echo Not found; else echo Found; fi
Found
$ if ! echo Wunderabcd | grep -q Wunderlist; then echo Not found; else echo Found; fi
Not found

1 Comment

Thank you for the elaborated answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.