example text $ echo "$line" original value \```
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.
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
LC_COLLATEis 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:
A variable can be scoped to a function:
This scope is separate from the shell scope, so we can even use the same variable outside the function:
Using the same variable for different things within the same script is not recommended, even when using local variables, but this at least makes the function reusable in other scripts and free of one kind of side effect.
Exported variables are scoped to the declaring and descendant shells. This basically means that once a variable is exported it is in context for the remainder of that script, including any subshells. This can be handy for consistency. For example, to ensure consistent locale handling in the entire script we can put
export LC_ALL=POSIX near the top. The flip side of this convenience is that these are effectively global variables — they should be used sparingly, when the convenience of having the variable available everywhere is more important than the added complexity in the context with the associated risk of unintended side effects.
In interactive shells variables such as
$USER are automatically exported — you can list the currently exported variables with
declare -x or its shorthand