0

I need the below bash script to do the following that when the gcc command returns an error, the script will stop looping and exit prematurely. And if the script is exiting prematurely it should return the value of 1 (failure), otherwise it will return 0 (success).

I tried doing this but I don't think my tries are good. I wrote my solution to the above in # Attempt : etc...

#!/bin/bash
# This script will be going through all C program files
ls *.c
gcc *.c -o Output.out

Attempt: command || exit 1 # exit 1 failure

./Output.out ls *.cc g++ *.cc -o SecOutput.out

Attempt: command || exit 1 # exit 1 failure

./SecOutput.out

Attempt: exit 0 # exit 0 success

1 Answers1

4

From the set man page:

-e Exit immediately if a command exits with a non-zero status.

So your script should begin with:

#!/bin/bash

set -e # exit on first error

dariofac
  • 1,042
  • If you put it at the beginning (just after the shebang), then the script will terminate at the first error encountered. If for example you put it after a command which is allowed to fail, then the script goes on. Hope it is clear. – dariofac Dec 30 '20 at 20:54