Red Hat Linux 7 Unleashed

Red Hat Linux 7 Unleashed

By William Ball

Variables

Linux shell programming is a full-fledged programming language and, as such, supports various types of variables. Variables have three major types: environment, built-in, and user.

A major difference between shell programming and other programming languages is that in shell programming, variables are not typecast. That is, you do not have to specify whether a variable is a number or a string, and so on.

Assigning a Value to a Variable

Say you want to use a variable called lcount to count the number of iterations in a loop within a shell program. You can declare and initialize this variable as follows:

Command Environment
lcount=0 pdksh and bash
set lcount = 0 tcsh

Shell programming languages do not use typed variables, so the same variable can be used to store an integer value one time and a string another time. This is not recommended, however, and you should be careful not to do this.

To store a string in a variable, you can use the following:

Command Environment
myname=Sanjiv pdksh and bash
set myname = Sanjiv tcsh

The preceding can be used if the string does not have embedded spaces. If a string has embedded spaces, you can do the assignment as follows:

Command Environment
myname='Sanjiv Guha' pdksh and bash
set myname = 'Sanjiv Guha' tcsh

Accessing Variable Values

You can access the value of a variable by prefixing the variable name with a $ (dollar sign). That is, if the variable name is var, you can access the variable by using $var.

If you want to assign the value of var to the variable lcount, you can do so as follows:

Command Environment
lcount=$var pdksh and bash
set lcount = $var tcsh

Share ThisShare This

Informit Network