Skip to content

SC2154 does not recognize variables declared in trap script #3287

@olivergondza

Description

@olivergondza

For bugs with existing features

Shellcheck reports variable used in trap statement is unassigned even if assigned earlier in the trap "script".

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

Mind the trap script is using single quotes - hence the variables are substituted during trap execution, not its declaration.

#!/usr/bin/env bash

trap 'exit_code=$?; echo >&2 "$0: Error on line "$LINENO": $BASH_COMMAND"; exit $exit_code' ERR
#!/usr/bin/env bash

trap 'let exit_code=$?; echo >&2 "$0: Error on line "$LINENO": $BASH_COMMAND"; exit $exit_code' ERR
#!/usr/bin/env bash

trap 'export exit_code=$?; echo >&2 "$0: Error on line "$LINENO": $BASH_COMMAND"; exit $exit_code' ERR

Here's what shellcheck currently says:

trap 'export exit_code=$?; echo >&2 "$0: Error on line "$LINENO": $BASH_COMMAND"; exit $exit_code' ERR
     ^-- SC2154 (warning): exit_code is referenced but not assigned.

Here's what I wanted or expected to see:

No errors 😎

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions