Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

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

2 Answers

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

share|improve this answer
add comment
up vote 1 down vote accepted

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.

share|improve this answer
1  
Please don't do that, use pgrep instead –  Ulrich Dangel Dec 4 '12 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. –  Forethinker Dec 4 '12 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... –  Gert van den Berg Dec 4 '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 5 '12 at 11:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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