Variables are the part of every script that holds information used by the script.
Many different types of variables can be used in a shell script. This module describes how to create and access those variables.
By the end of this module you will be able to:
Access information passed into a shell script on the command line
Use predefined shell and system variables
Access the value of environment variables
Create your own variables
Use different syntax in scripts to access information in variables
Work with string (text) and numeric data stored in variables
Create and use array variables
Shell Variables
Shell variables can be divided into two types:
shell environment variables
and user-defined variables.
Environment variables are used to make the environment settings for proper execution of shell commands.
Most of these variables are initialized in some of the system setup files.
When a user logs in, the system setup files (such as the .profile file) are executed and accomplish the initialization of those environment variables.
Usually, the system administrator writes the system setup files to set up a common environment for all users of the system.
The users, however, can customize their own shell environment by assigning different values to some or all of these variables in the setup file according to their demands.
When a command is executed as a child process of the login shell, a copy of environment variables is passed to it by the kernel.
Variables are how programming and scripting languages represent data. A variable is nothing more than a
label, a name assigned to a location or set of locations in computer memory holding an item of data.
Variables appear in arithmetic operations and manipulation of quantities, and in string parsing.
Variable Substitution
The name of a variable is a placeholder for its value, the data it holds. Referencing (retrieving) its value is
called variable substitution.
Let us carefully distinguish between the name of a variable and its value. If variable1 is the name
of a variable, then $variable1 is a reference to its value, the data item it contains.
The only times a variable appears "naked" -- without the $ prefix -- is when declared or assigned,
when unset, when exported, in an arithmetic expression within double parentheses (( ... )), or in the
special case of a variable representing a signal (see Example 32-5). Assignment may be with an = (as
in var1=27), in a read statement, and at the head of a loop (for var2 in 1 2 3).