Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fedy-cz opened this issue Apr 25, 2024 · 1 comment
Open

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

fedy-cz opened this issue Apr 25, 2024 · 1 comment

Comments

@fedy-cz
Copy link

fedy-cz commented Apr 25, 2024

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
Copy link
Author

fedy-cz commented Apr 25, 2024

Related: #2975

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant