Shell Variables   «Prev  Next»
Lesson 1

Working with Variables using Unix Shell

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:
  1. Access information passed into a shell script on the command line
  2. Use predefined shell and system variables
  3. Access the value of environment variables
  4. Create your own variables
  5. Use different syntax in scripts to access information in variables
  6. Work with string (text) and numeric data stored in variables
  7. Create and use array variables

Shell Variables

Shell variables can be divided into two types:
  1. shell environment variables
  2. 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.
bash$ variable1=23
bash$ echo variable1
variable1
bash$ echo $variable1
23

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).

Linux Shell Scripting