koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts
https://www.shellcheck.net
GNU General Public License v3.0
36.45k stars 1.78k forks source link

SC2251 - add ${PIPESTATUS[0]} check to exceptions #2974

Open fedy-cz opened 6 months ago

fedy-cz commented 6 months ago

Prepending statement with a ! operator is a common way to avoid errexit on a particular command.

SC2251 currently correctly warns that the the return code might not be checked. There is an exception to the rule where $? is checked afterwards. The problem is that the value of $? is inverted by the ! operator and it converts all the non-zero return codes to 0. One often needs to check the explicit return value of the original statement and a common way to do it is to check ${PIPESTATUS[0]} instead.

Consider for example the following common snippet (intended to check if getopt can be used on the system):

#!/bin/bash
set -o errexit -o pipefail -o noclobber -o nounset

# -allow a command to fail with !’s side effect on errexit
# -use return value from ${PIPESTATUS[0]}, because ! hosed $?
! getopt --test > /dev/null
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
  echo "I’m sorry, 'getopt --test' failed in this environment." >&2
  exit 1
fi

I suggest that checking ${PIPESTATUS[0]} could be considered equivalent to checking the $? and might be safely added to exceptions to this rule (SC2251)

fedy-cz commented 6 months ago

Related: https://github.com/koalaman/shellcheck/issues/2975