jlbroot
jlbroot

Reputation: 107

Variables comparision

I want to write a script with several commands and get the combination result of all them:

#!/bin/bash

command1; RET_CMD1=$(echo $?)

command2; RET_CMD2=$(echo $?)

command3; RET_CMD3=$(echo $?)

\#result is error if any of them fails

\#could I do something like:

RET=RET_CMD1 && RET_CMD2 && RET_CMD3 *<- this is the part that I can't remember how I did in the past..*

echo $RET

Thanks for your help!

Upvotes: 0

Views: 32

Answers (2)

TrebledJ
TrebledJ

Reputation: 9007

So to think about this...

we want to return 0 on success... or some other positive integer if an error occurred with one of the commands.

If no error occurred with any 3, they would all return 0, which means you would also return 0 in your script. Some simple addition can resolve this.

RET=$[RET_CMD1 + RET_CMD2 + RET_CMD3]   # !
echo $RET

You can also replace the first line (!) with logical or operator, as you mentioned.

RET=$[RET_CMD1 | RET_CMD2 | RET_CMD3]

Note that addition and logical or are different in nature. But you seemed to want the logical or...

Disadvantages of this setup: Not being able to trace where the error occurred from the return value. Tracing errors from either 3 commands will need to rely on other error output generated. (This is just a forewarning.)

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74685

I think you're just looking for this:

if ! { command1 && command2 && command3; }; then
  echo "one of the commands failed"
fi

The result of the block { command1 && command2 && command3; } will be 0 (success) only if all of the commands exited successfully. The semicolon is needed if the block is all written on one line.

There is no need to save the return codes to variables, or even to refer to $?, since if works based on the return code of a command (or list of commands).

Upvotes: 2

Related Questions