tags:

views:

82

answers:

4

I wanted to conditionally run a command as a background or foreground process, so I wrote something like this:

test $some_var; bg_suffix=&
long_command $bg_suffix

it doesn't work because bg_suffix is always empty whether it's been assigned or not.

But

test $some_var; bg_suffix="&"
long_command $bg_suffix

doesn't work either because now bg_suffix is interpreted as a string.

Any ideas how to solve this problem? Thanks!

+3  A: 

How about:

if [[ ${somevar} ]] ; then
    long_command &
else
    long_command
fi

or, if it is a long command you don't want to have to enter twice:

long_command=insert your big honking command here
if [[ ${somevar} ]] ; then
    ${long_command} &
else
    ${long_command}
fi

Just as an aside, I hope you're aware that the command sequence:

test ${condition}; x=2

will set x to 2 regardless of the test results. You may have meant to write:

test ${condition} && x=2
paxdiablo
Yes It's a long command otherwise I would go with your first snippet.Thanks for pointing out my mistake in using "test" command.
dennis2008
+2  A: 

did you try

eval (long_command $bg_suffix)

using bg_suffix="&"

ennuikiller
I get an error with this. I think you may need double quotes around the string being eval'ed. ??
paxdiablo
I also got an error with this but eval long_command $bg_suffix worked, thanks!
dennis2008
+1  A: 

I don't know why I am not able comment, but anyway

test $some_var; bg_suffix="&"

would cause bg_suffix to be set regardless of the result of test.

Murali
+3  A: 

Here is how to do it without using a quote-breaking eval

inBackground () {
  t=$1
  shift
  if $t; then
    "$@"&
  else
    "$@"
  fi
}

This lets you do something like:

inBackground false echo '$$'
inBackground true sleep 4

This gets around the problem that all the eval-based solutions have: new and sometimes impossible quoting rules. For example, try to pass the '$$' through eval. Because true and false are not significant to the parser they can be in variables and things will still work.

Of course, if you wanted shell metachars to work (say, you redirect i/o) then eval is better, or you need to define a procedure for the command, and if you define a procedure, you problem is solved:

complicated_command () {
    sleep 3
    echo replace this with something complex
}
do_background=true
$do_background && (complicated_command&) || complicated_command
DigitalRoss