11

I want to run my node app in background and curl simultaneously using && .I tried following but not work

node app.js &;curl localhost

and i tried another one

node app.js & && curl localhost

but both not working

1
6

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
4

The right keyword is &. No need of ;.

Example: first_script.sh & second_script.sh

In your case:

node app.js & curl localhost
1

Use parentheses to group the commands, then a &:

Syntax:

( command1 && command2 )&

Example:

( find $HOME > ~/find.log && date >> find.log )&
1
  • this does not work. command 2 never gets called if it does not finish Nov 14 '18 at 16:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.