I want to execute a set of commands optionally in background and with bash. Something like this
#!/bin/bash
BGR=""
if [ foo ] ; then
BGR=\&
fi
cmd1 $BGR
cmd2 $BGR
cmd3 $BGR
wait
But this doesn’t seem possible with bash. If foo is true, the commands evaluate to
+ cmd1 '&'
+ cmd2 '&'
+ cmd3 '&'
so the & is just another argument.
Is there any other way to achieve this? Besides code duplication, where I write if/then/else blocks with the different behavior.
You can move the if-else-clause to a function to avoid code duplication, e.g.: