Home > database >  Execute next command if previous command exited with 0 **OR** 1
Execute next command if previous command exited with 0 **OR** 1

Time:09-08

Culprit: diff. diff doesn't play well with && - it exits with code 1 if there are differences, and doesn't care that all you want is the content of the diff, regardless of whether it contains any differences or not - but but but you still want to terminate on true error conditions like ENOENT.

This is a bit of a code golf question. What is the tightest bash syntax that implements the intention "run next command if previous command exited with either 0 or 1 but not >1"?

Alternatively, is there a standard utility that can be used to execute a command and "remap" its exit code?

CodePudding user response:

diff file1 file2; (( $? < 2 )) && echo "Eureka"

or you COULD define a diff function like:

 diff() { command diff "$@"; rc="$?"; (( rc == 1 )) && rc=0; return "$rc"; }

and then diff file1 file2 would exit with status 0 instead of 1 if the diff command would exit 1.

I'd recommend if you're going to do that you use a different name for the function though, and just remember to call THAT when you need it, e.g.:

 my_diff() { diff "$@"; rc="$?"; (( rc == 1 )) && rc=0; return "$rc"; }

CodePudding user response:

Don't use &&, just check $? explicitly.

diff file1 file2
if [ $? -gt 1 ]
then exit 1
fi
  • Related