shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

recommend 'set -u' or alert on unset variables

Open jschauma opened this issue 9 years ago • 3 comments

If a script contains an unset variable, shellcheck should alert and recommend the use of 'set -u' and/or default values ("${VAR:-val}").

Current behaviour:

$ cat f.sh
#! /bin/sh
echo "${VAR}"
$ shellcheck f.sh
$ 

Desired example behaviour:

$ shellcheck f.sh

In /tmp/f.sh line 2:
echo "${VAR}"
     ^-- SC1234: Unbound variable. Use default value or ensure 'set -u' in your script.
$ 

jschauma avatar Apr 16 '16 15:04 jschauma

ShellCheck follows the convention that uppercase variables are shell/environment variables while lowercase ones are internal:

$ cat foo.sh
#! /bin/sh
echo "$var and $VAR"

$ shellcheck foo.sh

In foo.sh line 2:
echo "$var and $VAR"
      ^-- SC2154: var is referenced but not assigned.

This is to allow you to use more or less standard system variables without being nagged about it, such as $PATH, $SSH_CONNECTION or $PYTHONPATH.

This is poorly communicated though, and there's not much of a fallback.

ShellCheck should probably suggest lowercasing when a variable with an uppercase name is entirely overwritten and not exported, and use your suggestion for the rest.

koalaman avatar Apr 16 '16 17:04 koalaman

Perhaps .shellcheckrc could include a allow-list of (upper-case) variable names to exclude, and could then perform this check on all other variables encountered.

A slightly more dubious approach would be to see what's set in the current environment on invocation and use those variables as a default set…

Should ${SSH_CONNECTION:-} or ${PYTHONPATH:-} actually be excluded, though? They'll only be set in specific circumstances, and so non-defaulted use is likely a (common, admittedly) potential error?

srcshelton avatar Feb 04 '24 01:02 srcshelton

I see that this is likely mostly covered by the enable=check-unassigned-uppercase .shellcheckrc option.

srcshelton avatar Feb 04 '24 01:02 srcshelton