Shell Components   «Prev  Next»
Lesson 6Variables
ObjectiveExplain the use of variables in scripts.

Variables used in Unix Scripting

s Variables are used in programming to hold information that may change during the execution of the program or that you want to assign a name to for easy reference. You might set up some of this information as part of the shell script; some may be provided by the shell itself or by other programs.

Changeable information

When you need to keep track of information that might change as your script executes, you assign that information to a name, called a variable. You can then change the value of the variable, or check its current value at any time.

Naming Constants

Sometimes information is not expected to change, but you assign it to a variable so that throughout your shell script you can use a readable name like NumberOfAgents rather than seeing the number 415 and wondering what it means. This makes a script more readable and easier to troubleshoot.
If you do need to change a number that you thought was unchanging, you can alter it once in the script, where it is assigned to the variable.

System information

A great deal of information about your UNIX system is available within the shell by accessing system-defined variables. By testing the values of these variables (called environment variables), you can determine what actions to take in your script. These are similar to variables you create yourself, but they are predefined by the shell for your use. Later in this course, you will learn the details of how to create and access variables in shell scripts. The following diagram shows a few example variables with their use in a shell script.

Environment variable :

Name-value pairs containing values that are needed (and can be accessed) by any program within the environment simply by querying for the value of the environment variable's name.

System variable to return the Process ID of the script
  1. System variable to return the Process ID of the script
  2. System variable to return the first command line parameter.
  3. User-defined variable for counting in a loop.
  4. Environment variable containing the current user's home directory path.
  5. User-defined variable to hold a constant value referenced in the script.
  6. Environment variable containing the operating system name.
More Script Variables
The next lesson describes how control structures are used to manage which commands are executed in your shell scripts.

Ad Linux Shell Scripting