You are not logged in.
I've modified a tiny script that executes a program only if it's not already running.
#!/bin/bash
pgrep $1 > /dev/null || ($@ &)
It works fine for most things, except when I need the called command to include quotes. For example, say I called the script "run_once" and I was running this:
./run_once devmon --exec-on-drive "play -q mount.wav"
which actually calls:
devmon --exec-on-drive play -q mount.wav
which removes the quotes and breaks the command.
How could I fix this? Thanks for any input.
Last edited by ilikepie (2011-12-21 11:52:13)
Offline
#!/bin/bash
pgrep "$1" > /dev/null || { "$@" & }
I've replaced () with {} because there's no reason to run it in a subshell.
Note that although it might be good enough for your use case, `pgrep` (or anything relying on the name of a process) is not really reliable for anything.
This silver ladybug at line 28...
Offline
Hah, it was that simple. Thanks, problem solved!
I know pgrep isn't a good idea, but I just use that to start up a couple things when my window manager is ready. This prevents running the same program multiple times if the WM needs to restart.
Last edited by ilikepie (2011-12-21 11:55:52)
Offline
@lolilolicon
Would
pidof $1 >& /dev/null
if [ $? -ne 0 ]; then
$1 &
fi
be better?
Offline
@lolilolicon
Would
pidof $1 >& /dev/null if [ $? -ne 0 ]; then $1 & fi
be better?
Yes, I agree a `if` block looks cleaner. Your example could be simplified as
if ! pidof "$1" > /dev/null; then
"$@" &
fi
And I also think `pidof` is more accurate, the same as which can be done with `pgrep -x`.
As to $1 vs $@, it depends on the purpose I guess, but in either case, it should be quoted.
This silver ladybug at line 28...
Offline