How to stop the bash script when a command meets an error?

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

1 Answer

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
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like