Scope: Local Variables

Learn about local variables in detail.

We'll cover the following

Local variables

We considered user-defined variables. We can declare them in several ways. Depending on our choice, the new variable comes to the local scope or global scope (environment).

There are two ways to declare the global scope variable:

  1. Add the export command to the variable declaration.
  2. Pass the variable to the program when launching it. We can do it with the env utility when using a shell other than Bash.

If we do not apply any of these ways, our variable comes to the local scope. A variable of this kind is called a local variable and is available in the current instance of the interpreter. A child process (except a subshell) does not inherit it.

Here is an example. Let’s suppose that we declare the filename variable in the terminal window this way:

filename="README.txt"

Now, we can print its value in the same terminal window. The following echo command does that:

echo "$filename"

Try the commands discussed in this lesson in the terminal below.

Get hands-on with 1200+ tech skills courses.