How do I wait for a background process to complete?

5,776

As the error messages hint, the wait command won't try to look up the pid by the variable name for you (although as a built-in, it could theoretically do it).

You need to pass wait the actual pid values (or job numbers) as stored in the proc1 and proc2 variables. You do that by prepending $ to the variable names as usual. That will cause the shell to substitute the values for the variable names before passing them on to the wait command.

Share:
5,776

Related videos on Youtube

Dave
Author by

Dave

Updated on September 18, 2022

Comments

  • Dave
    Dave almost 2 years

    I'm using Amazon Linux with bash shell. I would like to run a couple of processes in the background, and then wait for them to complete (either with a success or error exit code) before proceeding. So I tried:

    node test.js 2>&1 | tee --append $TFILE1 &
    proc1=$!
    node SkyLocal.js 2>&1 | tee --append $TFILE2 &
    proc2=$!
    
    wait proc1
    rc1=$?
    wait proc2
    rc2=$?
    

    but I'm getting these errors:

    /home/jboss/.jenkins/jobs/myproject/workspace/automated-tests/nodejs/run_tests.sh: line 36: wait: `proc1': not a pid or valid job spec
    /home/jboss/.jenkins/jobs/myproject/workspace/automated-tests/nodejs/run_tests.sh: line 38: wait: `proc2': not a pid or valid job spec
    

    How do I capture the PID of the background process and then wait for the process to complete before continuing?

    • PSkocik
      PSkocik over 7 years
      wait $proc1 Don't forget the dollar sign.