I would like to run a program conditionally in the background, if the condition is met, we run it as a daemon, otherwise we wait for the result:
if [ -z "${CONDITION}" ]; then
echo "background" && npm install -g yarn &
else
echo "foreground" && npm install -g yarn
fi
is there a shorthand way to do this? (I assume in the else block, that given the syntax that this process will not run in the background). I guess we could also conditionally add "wait" instead of an "&" character.
Examples highlighting the use of background processes at the Bash command line Here we started a 1000 second sleep process in the background. If we want to put a process in the background, we can use the ampersand ( &) sign behind any command.
Users can execute the commands to run in the background if they append the “&” character. This will imply that while the commands are running, users still can take care of the relevant work alongside it, without any interruption. As an example, let’s check out the command to add numbers inside a text file.
The conditional statement is used in any programming language to do any decision-making tasks. This statement is also used in bash to perform automated tasks like another programming language, just the syntax is a little bit different in bash. Two types of conditional statements can be used in bash. These are, ‘If’ and ‘case’ statements.
Note that the process keeps running when it is placed in the background, which gives us the best of both worlds; the process is executing, and we get our command line back in the meantime! Great. We next place the process back in the foreground (as if there never was a background instruction) by using the fg (i.e. foreground) command.
I think your wait
idea is good. I can't think of a better way.
npm install -g yarn &
[ -n "$CONDITION" ] && { echo "waiting for install"; wait; }
Not sure that you want the echo
stuff or not, but if it's time consuming, you might want an indication.
HTH
Update: Simple script to show how it works
C=""
date
sleep 5s &
[ -n "$C" ] && { echo "waiting"; wait; }
date
If C=""
, you get an output like so:
Thu Dec 8 11:42:54 CET 2016
Thu Dec 8 11:42:54 CET 2016
(and of course, sleep 5s
is still running while your script is finished)
If you set C="something"
, you get:
Thu Dec 8 11:42:42 CET 2016
waiting
Thu Dec 8 11:42:47 CET 2016
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With