Home > Software design >  Cannot stop BASH when using of && and || operators
Cannot stop BASH when using of && and || operators

Time:04-06

I would like to stop my BASH if the commands have any errors.

make clean || ( echo "ERROR!!" && echo "ERROR!!" >> log_file && exit 1 )

But seems like my BASH still keeps going. How do I put exit 1 in the one-line operators

I am very new to BASH, any help is appreciated!

CodePudding user response:

exit 1 exits from the subshell created by (), not the original shell. Use {} to keep the command group in the same shell.

Don't use && between commands unless you want to stop as soon as one of them fails. Use ; to separate commands on the same line.

make clean || { echo "ERROR!!" ; echo "ERROR!!" >> log_file ; exit 1 ;}

Or just use if to make it easier to understand.

if ! make clean
then
    echo "ERROR!!"
    echo "ERROR!!" >> log_file
    exit
fi

CodePudding user response:

You have the direct solution in Barmar's answer. An alternative if you want to check multiple commands in a similar way could be to define a function which could be reused:

die() {
    echo "ERROR: $@"
    echo "ERROR: $@" >> log_file
    exit 1
}

make clean || die "I left it unclean"
make something || die "something went wrong"

or, if you want the script to end at first sign of trouble, you could use set -e

set -e

make clean     # stops here unless successful
make something # or here if this line fails etc.

You may want to log an error message too, so you could install a trap on ERR. errfunc would here be called before exiting the script and the line number where it failed would be logged:

errfunc() {
    echo "ERROR on line $1"
    echo "ERROR on line $1" >> log_file
}

trap 'errfunc $LINENO' ERR
set -e

make clean
make something
  • Related