How to run a program in background and also using && to execute another command
You may want
echo first && echo second && echo third & wait
which gives you the output (similar to)
[1] 4242
first
second
third
[1]+ Done
The last &
puts the whole previous command in a pipeline/job. That job consists of three commands chained together using the shell boolean expression. If one of those returns false, that should terminate the chain. But they will all run in the background.
The problem with running the first program in the background but the second one in the foreground is that the second command does not know if the first completed successfully. When you put a program in the background, its status will be 0 unless the program could not be executed to begin with. So the following really does not make sense:
( start_webservice & ) && curl localhost
Neither does this make sense:
start_webservice & test "$?" = 0 && curl localhost
Simply start the background service and unconditionally test it. More than likely, you will want to wait for a little while before making that test:
start_webservice &
success=0
tries=5
pause=1
while [ $success = 0 -a $tries -gt 0 ]; do
sleep $pause
let tries=tries-1
curl localhost && success=1
done
if [ $success = 0 ]; then
echo "Launch failed"
fi
The right keyword is &
. No need of ;
.
Example: first_script.sh & second_script.sh
In your case:
node app.js & curl localhost