Search code examples
reactjsbashnpmbuild

stop bash script if react build fails


I have a couple of deployments that has broken production, since the bash script continues if the build fails. How can I make sure that the script exits should the npm run build fail?

#!/usr/bin/env bash
source .env
ENVIRONMENT="$REACT_APP_STAGE"
if [ "$ENVIRONMENT" != "production" ]; then
    echo "improper .env NODE_ENV"
    exit
fi
git pull origin master
npm i
npm run build
rm -r /var/www/domain_name.dk/html/*
mv /var/www/domain_name.dk/website/build/* /var/www/domain_name.dk/html/

Solution

  • It is surprisingly easy:

    #!/usr/bin/env bash
    source .env
    ENVIRONMENT="$REACT_APP_STAGE"
    if [ "$ENVIRONMENT" != "production" ]; then
        echo "improper .env NODE_ENV" >&2  # Errors belong on stderr
        exit 1
    fi
    git pull origin master
    npm i
    npm run build || exit  # Exit if npm run build fails
    ...
    

    By using the short-circuiting || operator, if npn run build fails, then the command on the right side excutes. exit returns the exit status of the last executed command, so the script will exit with the same failure code that npn run build exited with. If npm run build succeeds, then the exit is not executed.