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

The "Use && exit 1" for SC2251 can result in a wrong exit code #3121

Open
bdrung opened this issue Jan 13, 2025 · 3 comments
Open

The "Use && exit 1" for SC2251 can result in a wrong exit code #3121

bdrung opened this issue Jan 13, 2025 · 3 comments

Comments

@bdrung
Copy link

bdrung commented Jan 13, 2025

The "Correct code" from https://github.com/koalaman/shellcheck/wiki/SC2251 can result in a wrong exit code. I stumbled over this issue while working on https://salsa.debian.org/kernel-team/initramfs-tools/-/merge_requests/144

Here's a snippet that shows the problem:

#!/bin/sh
set -e
! test "${1-}" = "fail"

Shellcheck will correctly complain about SC2251, but this script works correctly (as long as the ! check is the last command):

$ ./example; echo $?
0
$ ./example fail; echo $?
1

Here's what shellcheck recommends:

https://github.com/koalaman/shellcheck/wiki/SC2251 recommends to change the code to:

#!/bin/sh
set -e
test "${1-}" = "fail" && exit 1

This causes the script to always exit with error code 1:

$ ./example; echo $?
1
$ ./example fail; echo $?
1

Here's what I suggest:

Adding || exit 1 would work for this case and probably for all other cases:

#!/bin/sh
set -e
! test "${1-}" = "fail" || exit 1

Then the exit code will be 0 again for the "successful" case:

$ ./example; echo $?
0
$ ./example fail; echo $?
1
@brother
Copy link
Collaborator

brother commented Jan 13, 2025

Reasonable. The wiki is open for edits.

@bdrung
Copy link
Author

bdrung commented Jan 13, 2025

The error message of shellcheck needs to be changes as well. From

This ! is not on a condition and skips errexit. Use && exit 1 instead, or make sure $? is checked.

to something like:

This ! is not on a condition and skips errexit. Add || exit 1 or make sure $? is checked.

@bdrung bdrung changed the title The "Correct code" for SC2251 can result in a wrong exit code The "Use && exit 1" for SC2251 can result in a wrong exit code Jan 13, 2025
@bdrung
Copy link
Author

bdrung commented Jan 13, 2025

I updated the wiki.

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

2 participants