Search code examples
bashshellbackground-process

How do I get entire bash script to exit (including backgrounded processes) if a bash command succeeds or fails?


I have the following bash script. I would like to run three commands

  1. The first command starts up a front-end web server, which I would like to be backgrounded.
  2. The second command starts up a back-end web server, which I would like to be backgrounded.
  3. The third command runs an npm script that tests the web application.

The third command will exit with an error code if the tests were unsuccessful.

How do I get my entire bash script to exit with an error code if the third command finishes with an error? If the third command finishes without an error, I want my bash script to exit with a 0 error code.

Below is my attempt (the script doesn't work as intended). My intention is for all backgrounded processes to end after npm run my-special-command. If npm run my-special-command results in an error code, I want my script to exit with that error code. Otherwise, I want my script to exit with a 0 error code.

#!/bin/bash
history-server dist -p 8080 &
nodemon server &
npm run my-special-command || exit 1
exit 0

Solution

  • You could use a command substitution:

    # save PID of background process
    history-server dist -p 8080 &
    history_server_pid=$!
    
    # if command succeds exit 0; else terminate background process and exit 1 
    if [ $(npm run my-special-command 2>/dev/null) ]; then
        exit 0
    else
        kill $history_server_pid
        exit 1
    fi
    

    if the command succeeds the script will exit with status 0, or 1 otherwise.