开发者

BASH: Assign '&' to variable NOT as string

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 wo开发者_开发技巧rk 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!


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


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


did you try

eval (long_command $bg_suffix) 

using bg_suffix="&"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜