How to Restrict Variable and Function Scope in Bash Scripts

Variable scope#

Aim of this section: Understand how variables are scoped to avoid namespace pollution and associated bugs.

It can get really difficult to tell what is happening when there is a lot of global state. Here we’ll look at some ways to reduce the scope of variables to avoid namespace pollution.

Command scope#

A variable assigned in the prefix of a command is scoped to that command. For example, it is common practice to ensure consistent sorting by setting the $LC_COLLATE variable. Compare

to

LC_COLLATE is a special locale setting. “POSIX” is a special locale which is available on all modern *nix systems, which makes it ideal for portability.

Please note that the assignment becomes part of the context of the command, not the shell, so assigning one before a shell builtin does not work:

Function scope#

A variable can be scoped to a function:

This lesson preview is part of the The newline Guide to Bash Scripting course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to The newline Guide to Bash Scripting, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course The newline Guide to Bash Scripting