views:

218

answers:

2

I added a shortcut to an application in ubuntu. Each time i press shortcut keys, a new instance of application is created. I need only one instance, what script i can use to open the existing instance of application or creates a new one if the application is not running?

+2  A: 

It depends greatly on the application. The most trivial case would be the known process name which can only be run by you (that is, no stray instances on the system):

pidof applicaton || /usr/bin/application

Opening an existing application may get tricky and, again, depends on the application. I'd suggest that you take a look at alltray thingie and pay special attention to the alltray --help output.

Edit by ypnos: If you want to restrict this to the current user only, you should use pgrep instead of pidof, like this:

pgrep -u `id -u` application || application
Michael Krelin - hacker
Thanks, works great.
Mehdi Sadeqi
+1  A: 

You can also try a script like this:

#! /bin/bash
user=`id -un`
lock=/tmp/$user-$1-lock
if [ -e $lock ]; then
    exit #app is already running
fi

touch $lock
$@
rm $lock

If you called the script 'runner.sh', you can use it like this:

runner.sh xcalc

Is for cases where pidof doesn't work. Else go for hacker's solution, which is also more robust.

ypnos
The script worked great also, thank you.
Mehdi Sadeqi
As much as i understand your script it ensures that only one instance of application can be running system wide even if there are many users logged on and using the same application?
Mehdi Sadeqi
No, the lock file is bound to the user, see the variable $user in the script.
ypnos