Skip to content
Lucas Larson edited this page Feb 2, 2022 · 3 revisions

In POSIX sh, local is undefined.

Problematic code:

myfunc() {
  local i=0
  ..
}

Correct code:

In POSIX sh, you can adopt some convention to avoid accidentally overwriting variables names, e.g. prefixing with the function name:

myfunc() {
  _myfunc_i=0
  ..
}

You can also unset the variable at the end of the function:1

myfunc() {
  i=0
  ..
  unset i
}

You can also use POSIX’s set +a or set +o allexport which prevents the “export attribute” from being “set for each variable to which an assignment is performed”:2

myfunc() {
  set +a || set +o allexport # either will work – don’t use both.
  i=0
  ..
  set -a || set -o allexport # optionally undo `set` modifications
}

Rationale:

local is supported in many shells, including bash, ksh, dash, and BusyBox ash. However, strictly speaking, it's not POSIX.

Exceptions:

Since quite a lot of real world shells support this feature, you may decide to ignore the warning.

Related resources:

  1. Shell Command Language § unset (archived)
  2. Shell Command Language § Description (archived)
  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally