shellcheck
shellcheck copied to clipboard
SC2317: false-positive with EXIT trap in subshell?
For bugs
- Rule Id (if any, e.g. SC1000): SC2317, SC2317, SC2317, SC2317
- My shellcheck version (
shellcheck --version
or 'online'): online - [x] I tried on shellcheck.net and verified that this is still a problem on the latest commit
- [ ] It's not reproducible on shellcheck.net, but I think that's because it's an OS, configuration or encoding issue
For new checks and feature suggestions
- [x] shellcheck.net (i.e. the latest commit) currently gives no useful warnings about this
- [x] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related
Here's a snippet or screenshot that shows the problem:
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
(
tmp=$(mktemp -d)
cleanup() {
if [[ -d $tmp ]]; then
rm -rf "$tmp"
fi
printf "removed tmp: %s\n" "$tmp"
}
trap cleanup EXIT
printf "tmp is %s\n" "$tmp"
)
printf "After subshell\n"
Here's what shellcheck currently says:
Line 10 SC2317: Command appears to be unreachable. Check usage (or ignore if invoked indirectly).
Line 10 SC2317: Command appears to be unreachable. Check usage (or ignore if invoked indirectly).
Line 11 SC2317: Command appears to be unreachable. Check usage (or ignore if invoked indirectly).
Line 13 SC2317: Command appears to be unreachable. Check usage (or ignore if invoked indirectly).
Here's what I wanted or expected to see:
This looks like a false positive, because running that script gives the expected outcome:
tmp is /tmp/tmp.coTHszefaD
removed tmp: /tmp/tmp.coTHszefaD
After subshell
I don't think that case is covered in the other bug reports.
The following, in this case equivalent, script doesn't trigger the warning:
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
tmp=$(mktemp -d)
cleanup() {
if [[ -d $tmp ]]; then
rm -rf "$tmp"
fi
printf "removed tmp: %s\n" "$tmp"
}
(
trap cleanup EXIT
printf "tmp is %s\n" "$tmp"
)
printf "After subshell\n"