-1

I have written a script to run some linux commands and capture the exceptions in an if clause and output the results. Basically each of the variables in the below excerpt of the code represent the command execution status and i want to exit the script successfully if all commands are executed succesfully. Otherwise i want to exit with one. While testing the script i had intentionally made on command fail and the output of one variable for example X8 is 1. In this scenario the below is not working as expected. It's showing me the success message instead of script failed message. Not sure why

if [ $X1 != 0 ] &&  [ $X2 != 0 ] &&  [ $X3 != 0 ] && [ $X4 != 0 ] && [ $X5 != 0 ] && [ $X6 != 0 ] && [ $X7 != 0 ] && [ $X8 != 0 ];
then echo "script failed"; exit 1;     
else echo "success"; fi;
  • 1
    You should use -ne for integer tests I think. Chaining with && requires all variables to be non-zero to get failure; don't you want || here? – steeldriver Nov 3 '16 at 19:46
  • 1
    You might consider (assume bash/ksh/zsh): if ((x1+x2+x3+x4+x5+x6+x7+x8 > 0)) – glenn jackman Nov 3 '16 at 20:40
  • 1
    Or, keep one variable that accumulates the exit status of your commands: ((status += $?)). Or, use set -e which will abort your script as soon as a command exits with a non-zero status. – glenn jackman Nov 3 '16 at 20:44
0

At the top of your script, add this:

trap 'echo "Error $? at $LINENO; aborting." 1>&2; exit $?' ERR

Then, anytime anything throws an uncaught error, the script will bail with the above message and exit with the exit code of the error. You can change $? to 1 if you really want to use an exit code of 1 for any error.

0

First of all, you are using [ which is short hand for test. From man test:

  STRING1 != STRING2
         the strings are not equal

You're using wrong tool for the job. What you need is

 INTEGER1 -eq INTEGER2
         INTEGER1 is equal to INTEGER2

Second, you have multiple conditions to test here. Instead of using one lengthy if statement , try to sum the output of each variable, as glenn suggested in comments, and test that. Alternatively, evaluate the output of each command right after it exist. There's no point in running others, if you're going to quit because that command's output anyway.

Here's a looping approach:

for i in $X1 $X2 $X3 ; 
do 
    [ $i -ne 0 ] && { echo "something failed"; exit 1; }
done
echo "Everything OK"

The trick here is that you're doing same test for each and every one of the variables, and if that test fails, the script will never get to the "Everything OK" part

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.