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.

4
  • What is printed if you remove the > /dev/null?
    – Mikel
    Dec 4, 2012 at 4:36
  • no, still does not work. Once again if part is fine, the problem occurs after the else statement. Dec 4, 2012 at 4:48
  • I wonder if $($1) would fix anything. Couldn't hurt to try.
    – Jodie C
    Dec 4, 2012 at 4:57
  • 2
    It didn't ask "does it work", I said "what does it print"?
    – Mikel
    Dec 4, 2012 at 5:11

2 Answers 2

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.

4
  • 1
    Please don't do that, use pgrep instead Dec 4, 2012 at 7:04
  • I am guessing this is to avoid the race condition, 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. Dec 4, 2012 at 7: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... Dec 4, 2012 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. Dec 5, 2012 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .