Shellcheck: recommend 'set -u' or alert on unset variables

Created on 16 Apr 2016  路  1Comment  路  Source: koalaman/shellcheck

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

Most helpful comment

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.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mechalynx picture mechalynx  路  5Comments

ymkjp picture ymkjp  路  3Comments

erichelgeson picture erichelgeson  路  5Comments

sobolevn picture sobolevn  路  4Comments

nathaniel112 picture nathaniel112  路  4Comments