[BUG] false `SC2218` when have `defer` like behavior
Author: loynoirCreated Oct 21, 2025Updated Sep 18, 2026
bug
false SC2218 when have defer like behavior
For bugs with existing features
- Rule Id (if any, e.g. SC1000): SC2218
- My shellcheck version (
shellcheck --versionor "online"):
ShellCheck - shell script analysis tool
version: 0.11.0
license: GNU General Public License, version 3
website: https://www.shellcheck.netThe rule's wiki page does not already cover this (e.g. https://shellcheck.net/wiki/SC2086)
I tried on https://www.shellcheck.net/ and verified that this is still a problem on the latest commit
Here's a snippet or screenshot that shows the problem:
#!/usr/bin/env bash
trap_add_cleanup() {
echo simulate trap add cleanup "$@"
}
main() {
local tmpfile
tmpfile="$(mktemp /tmp/tmp.reproduce.XXXXXXXXXX)"
trap_add_cleanup rm "${tmpfile:?}"
# region heredoc
cat >"${tmpfile:?}" <<'EOF'
echo line1
echo line2
EOF
# endregion heredoc
local expected
expected=$(
# region heredoc
cat <<'EOF'
line1
line2
EOF
# endregion heredoc
)
if [ "$(bash "${tmpfile:?}")" == "${expected:?}" ]; then
echo OK
else
echo ERR
fi
}
main "$@"Here's what shellcheck currently says:
$ shellcheck reproduce.sh
In reproduce.sh line 11:
trap_add_cleanup rm "${tmpfile:?}"
^-- SC2218 (error): This function is only defined later. Move the definition up.
For more information:
https://www.shellcheck.net/wiki/SC2218 -- This function is only defined lat...Here's what I wanted or expected to see:
No error.
Related
This is sub issue of https://github.com/koalaman/shellcheck/issues/3290
Open another issue because this sub issue
- have smaller reproduce
- have more describe-able behavior:
deferlike behavior
Source: koalaman/shellcheck