coding style – Which technical criteria are to be considered for the “way” of a conditional statement

User @kevinnls recently asks me here why i choose one way from another in a ternary logical equality conditional statement.

That seems an interesting question for Software Engineering SE, a question for which i haven’t found past matches on SE.

To summarize it, lets take the example of the check of the exit status from the GNU grep command. The GNU grep will exit with the following exist status :

  • 0 if it has found one or more lines matching the given pattern in the given file.
  • 1 if it can’t find a line matching the given pattern in the given file.
  • 2 if it encounters an error while processing the given file.

For reference, it can be illustrated with the following shell commands :

$ echo "text" > file
$ grep text file
text
$ echo $?
0
$ grep notext file
$ echo $?
1
$ grep text nofile
grep: nofile: No such file or directory
$ echo $?
2

With this example, if we want to check the exit status of a grep command in a shell script, we can make a conditional test on the exist status first focused on its success in a one liner ternary form (i choose ternary form for simplicity) :

( <grep command> ) && { success statements } || ( ( $? = 1 ) && { failure statements } || { error statements } )

But we could also express it with that one liner ternary form :

( <grep command> ) && { success statements } || ( ( $? != 2 ) && { failure statements } || { error statements } )

And the question is then which technical criteria should be considered when choosing between ( $? = 1 ) and ( $? != 2 ) ?