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
$ printf '%s\n' a A | LC_COLLATE=en_US.utf8 sort
to
$ printf '%s\n' a A | LC_COLLATE=POSIX sort
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:
$ name=Smith echo "$name"
Function scope#
A variable can be scoped to a function:
printf '> %s\n' "$line"
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.
Get unlimited access to The newline Guide to Bash Scripting, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
