6

I have a gnome-run application in my home folder. I have now added the application to run when I press Meta+R (I added it in in CCSM). I run the application by executing ./gnome-run in my home folder.
I can't find any trace of the application process in the output of ps -A.

The problem is that if I have the gnome-run program open and I press the key combination I want the application to close. Is there a way to create a bash file that checks if the applications is running? If it is then close it, else launch it.

1
  • have you tried pgrep? eg pgrep xterm returns the pids of my running xterm's. You could check if your app is already running using this (run pgrep yourapp and check if it's return code is 0 or 1 using echo $?). – romeovs Apr 1 '12 at 18:16
6

This shell script should handle the starting and stopping of any program:

#!/bin/bash

BASECMD=${1%%\ *}
PID=$(pgrep "$BASECMD")
if [ "$?" -eq "0" ]; then
    echo "at least one instance of "$BASECMD" found, killing all instances"
    kill $PID
else
    echo "no running instances of "$BASECMD" found, starting one"
    $1
 fi

let's say you saved it under ~/mystarter, you can run any command with it using ~/mystarter <name>, eg in your case, bind Meta+R to:

~/mystarter gnome-run

and make sure the script is executable: chmod u+x ~/mystarter. Also it's probably best to put it somewhere in your PATH, so you don't have to type it's full location every time.

As for the fact that gnome-run doesn't show up in ps -A, make sure that gnome run itself isn't a script that launches the actual process. Check if there is a difference between ps -A | wc -l before and after launching it (this counts all running processes).

Edit:

Since you've accepted the answer, I thought I'd add support for running commands that have commandline arguments, so that this might become a place of reference. Run a command like so:

 ./mystarter 'cmd args'

eg:

./mystarter 'ncmpcpp -c ~/.ncmpcpp'

The command just looks up ncmpcpp to see if it's running already, but executes the full command (with arguments) when ncmpcpp wasn't running.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.