1

I have a following simple script called single-instance that executes the given command if there is no process under that command running. If I hard-code the command after the else statement, it has no trouble running, but if I substitute the hard-coded command with $1 or $@, I get no new instance of the command. Is there a security mechanism in bash to prevent such command?

#!/bin/bash
if ps ax | grep -v grep | grep $1 > /dev/null;then
    wmctrl -xa $1
else
    # works fine if I switch $1 to terminator
    $1
fi

The if statement part works fine. I only get one instance of the process as long as I invoke it using this script.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Forethinker
  • 1,349
  • 13
  • 25

2 Answers2

1

Grep sees the command name that is invoked by 'single-instance' I added daemon in the grep option because some programs have daemon process running on even though its instance on the Window Manager does not exist.

#!/bin/bash
if ps -fp $(pgrep -d, "$1") egrep -v "single-instance|daemon" | grep $1;then
    wmctrl -xa $1
else
    $1
fi

Thanks Mikel for guiding me to figure it out.

Forethinker
  • 1,349
  • 13
  • 25
  • 1
    Please don't do that, use `pgrep` instead – Ulrich Dangel Dec 04 '12 at 07:04
  • I am guessing this is to avoid the [race condition](http://unix.stackexchange.com/questions/3340/how-can-i-see-what-processes-are-running), right? If so, how can I differentiate between the daemon process and the running process? For example, thunar does not work with if (pgrep $1) because of this. – Forethinker Dec 04 '12 at 07:23
  • 1
    `ps -fp $(pgrep -d, "$1")|egrep -v "single-instance|daemon"` Or `pgrep -f "$1\$"` (to exclude instances where the process have any parameters...), although it might be somewhat fragile... – Gert van den Berg Dec 04 '12 at 13:52
  • I edited my answer accordingly. My previous comment is erroneous (once again!) because all windows of thunar are handled by one process. – Forethinker Dec 05 '12 at 11:52
0

What are you trying to do? Keep some type of daemon running all the time? Perhaps you should take a look at systemd.

vonbrand
  • 18,156
  • 2
  • 37
  • 59