"Variabilize" the ampersand (background a process)

You can flip things and variabilise “foregrounding”:

FOREGROUND=fg
sleep 5 & ${FOREGROUND}

Set FOREGROUND to true or empty to run the process in the background. (Setting FOREGROUND to true to run in the background is admittedly confusing! Appropriate variable names are left as an exercise for the reader.)


You would probably have to use eval:

eval "sleep 5" "$BCKGRND"

eval causes the shell to re-evaluate the arguments given. A literal & would therefore be interpreted as & at the end of a command and not as an argument to the command, putting the command in the background.


It's not possible to use a variable to background the call because variable expansion happens after the command-line is parsed for control operators (such as && and &).

Yet another option would be to wrap the calls in a function:

mayberunbg() {
  if [ "$BCKGRND" = "yes" ]; then
    "$@" &
  else
    "$@"
  fi
}

... and then set the variable as needed:

$ BCKGRND=yes mayberunbg sleep 3
[1] 14137
$
[1]+  Done                    "$@"
# or
$ BCKGRND=yes
$ mayberunbg sleep 3
[1] 14203
$
[1]+  Done                    "$@"
$ BCKGRND=no mayberunbg sleep 3
# 3 seconds later
$