#3331·shellcheck

[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 --version or "online"):
bash
ShellCheck - shell script analysis tool
version: 0.11.0
license: GNU General Public License, version 3
website: https://www.shellcheck.net

Here's a snippet or screenshot that shows the problem:

bash
#!/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:

bash
$ 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

  1. have smaller reproduce
  2. have more describe-able behavior: defer like behavior