RatDon
RatDon

Reputation: 3543

bash command clubbing: get specific command's exit status

I've a command clubbing of 3 commands as below.

do A && do B || undo A

Here if do A fails, it'll return with non-zero exit status. If it succeeds, it goes to do B. If do B succeeds, it is zero exit status which is expected. But if it fails, it goes to undo A which succeeds and do B's exit status (which in this case will be a non-zero) is lost which shows the actual failure. So the whole commands exit status will be 0 though there is a failure.

Any way is it possible to get the do B's exit status in the above statement?

I know this can be easily done with if else. I'm just curious about a one-liner.

Upvotes: 1

Views: 58

Answers (1)

soulmerge
soulmerge

Reputation: 75714

If you don't need B's exact error code, you can return an error code explicitly by invoking /bin/false, or bash's builtin false:

do A && do B || ( undo A && false )

Otherwise, you can store the exact error code and return that value, although that is a bit ugly as a one-liner:

do A && do B || ( CODE=$? ; undo A; exit $CODE )

The above works by spawning a subshell using parantheses.

Upvotes: 2

Related Questions