Variables

Variables are mechanisms we have for storing and retrieving information. Variables are labeled locations in memory that you can name, store data into, and retrieve data from.

Variable names may consist of alphabetic, numeric and underscore characters, but cannot start with a digit.  To create a variable and assign a value, use the form:  variable_name=value.

Note:  There should be no space on either side of the equal sign.

You can retrieve the stored values using the following:


Order of Command Line Actions

  1. Sets up redirection (e.g. using the greater than sign or pipe)
  2. Variable substitution
  3. Wildcard expansion (*, $, [ ], etc.)
  4. Command execution

Example 1

Example 2

Example 3


Variables with { }

You can use “curly brackets” ( { } ) to control what the command line interprets as the name of a variable.  For example:

However,


Variables in Scripts

If you declare a variable in a script, when you execute the script in the usually fashion, the variable only exists while the script is running.

If you declare a variable in the shell, a script that you execute cannot use it, unless you “export” the variable first.  An exported variable can be used in a script, but if the script changes the variable, the variable will not keep the change after the script is finished.  You can export a variable when it is created or after it has been created.