Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally run process in background with bash

Tags:

bash

sh

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.

like image 235
Alexander Mills Avatar asked Dec 08 '16 07:12

Alexander Mills


People also ask

How do I run a process in the background in Bash?

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.

How to execute commands in the background in Linux?

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.

What is a conditional statement in Bash?

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.

What happens when a process is placed in the background?

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.


1 Answers

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
like image 120
tgo Avatar answered Oct 12 '22 20:10

tgo