1

I have shell file (deploy.sh) do the following commands:

  npm run build:prod

  docker-compose -f .docker/docker-compose.ecr.yml build my-app

  docker-compose -f .docker/docker-compose.ecr.yml push my-app

  aws ecs update-service --cluster ...

I want to stop the execution of the bash when error occurred from one of the commands.

Which command does that in shell?

Michele Dorigatti
  • 616
  • 1
  • 5
  • 15
Jon Sud
  • 5,117
  • 3
  • 28
  • 63

3 Answers3

3

If you want to test the success or failure of a command, you can rely on its exit code. Knowing that each command will return a 0 on success or any other number on failure, you have a few options on how to handle each command's errors.

|| handler

npm run build:prod || exit 1

if condition

if docker-compose -f .docker/docker-compose.ecr.yml build my-app; then
  printf "success\n"
else
  printf "failure\n"
  exit 1
fi

the $? variable

docker-compose -f .docker/docker-compose.ecr.yml push my-app
if [ $? -gt 0 ]; then
  printf "Failure\n"
  exit 1
fi

traps

err_report() {
    echo "Error on line $1"
}
trap 'err_report $LINENO' ERR

aws ecs update-service --cluster ...

set -e

To globally "exit on error", then set -e will do just that. It won't give you much info, but it'll get the job done.

James Tomasino
  • 3,357
  • 1
  • 18
  • 37
2

You can use set -e to exit on errors. And even better, you can set -e and use a trap function.

  #!/bin/bash
  set -e
  trap 'catch $? $LINENO' EXIT
  catch() {
   echo "catching!"
   if [ "$1" != "0" ]; then
     # error handling goes here
     echo "Error $1 occurred on $2"
   fi
  }

  npm run build:prod

  docker-compose -f .docker/docker-compose.ecr.yml build my-app

  docker-compose -f .docker/docker-compose.ecr.yml push my-app

  aws ecs update-service --cluster ...

source: https://medium.com/@dirk.avery/the-bash-trap-trap-ce6083f36700

aclowkay
  • 2,561
  • 1
  • 23
  • 48
1

Did a fast search on Google and it seems there isnt. Best is to use && or || or if ... else blocks see links below:

SO-Try Catch in bash and Linuxhint

Hope this helps

Carel Kruger
  • 41
  • 1
  • 5