You are not logged in.

#1 2011-12-21 10:52:15

ilikepie
Member
Registered: 2009-10-28
Posts: 38

[SOLVED] Bash script: quotes in arguments disappear with $@

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

#2 2011-12-21 11:23:21

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: [SOLVED] Bash script: quotes in arguments disappear with $@

#!/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

#3 2011-12-21 11:51:56

ilikepie
Member
Registered: 2009-10-28
Posts: 38

Re: [SOLVED] Bash script: quotes in arguments disappear with $@

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

#4 2011-12-23 21:13:10

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [SOLVED] Bash script: quotes in arguments disappear with $@

@lolilolicon

Would

pidof $1 >& /dev/null
if [ $? -ne 0 ]; then
 $1 &
fi

be better?

Offline

#5 2011-12-24 03:09:01

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: [SOLVED] Bash script: quotes in arguments disappear with $@

karol wrote:

@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

Board footer

Powered by FluxBB