Shell Variables

Team-Fly    

Solaris™ Operating Environment Boot Camp
By David Rhodes, Dominic Butler
Table of Contents
Chapter 5.  Shells


Programming languages allow the creation of variables as a mechanism to store data for later manipulation, and UNIX shells are no different. The way shell variables are assigned is different depending on the shell being used. Bourne Shell variables are assigned by simply entering the name of the variable followed by an equal sign and the value you wish to assign to it. They do not need to be defined first and therefore there is no need to say what type of data the variable will hold before it is assigned a value. If a variable holds a string of characters, you may manipulate it as you would the string of characters that was assigned to it, but you may not perform arithmetical operations on it. If the same variable were then to have a number assigned to it, you would be able to perform arithmetic on it.

The following example shows the assignment of a number of shell variables:

 $ greeting=hello $ age=21 $ formalGreeting="Good Morning" $ 

Here we have created three variables. The variable name is the word to the left of the equal sign and the value assigned is to the right. In each case, if the variable had already existed its original value would be replaced with the value we assigned above. If it didn't previously exist, the shell would create it for us. In the final example we wanted to include a space in the variable value so we put quotes around the whole string. We can use any combination of letters and numbers for shell variable names, but we cannot use a number as the first character.

Using Shell Variables

We have seen that setting shell variables is a straightforward procedure. We just need to remember not to put any spaces around the equal sign, and if we want to include spaces in what we are assigning we should use quotes.

Using a variable is also straightforward. We simply put a dollar sign before the variable name and the shell will replace it with the value assigned to it:

 $ firstname=dominic $ lastname=butler $ echo $firstname dominic $ echo $lastname butler $ echo $firstname $lastname dominic butler $ 

We can mix variables with straight text in a similar way:

 $ echo My surname is $surname and my first is $firstname My surname is butler and my first is dominic $ 

The shell can tell which are the variable names since they begin with a dollar symbol and the last character of the name is followed by a space. However, if we didn't want to display a space between the contents of a variable and the following text, the shell would have a bit of a job knowing where the variable name ended and the text began:

 $ name=fred echo $name fred $ echo $namedy $ 

Here we wanted to display the contents of the variable name followed by the text "dy" with no space between. The trouble ishow does the shell know that? It thinks we want to display the contents of a variable called "namedy," which it sees does not exist so it replaces it with an empty string. To do this, we need a way of telling the shell where the variable name ends; fortunately we can do this by using curly braces:

 $ name=fred $ echo ${name}dy freddy $ 

Now there is no confusion at all. The shell knows exactly what we want as we have specifically told it that the variable is called "name."

Using Variables in Shell Scripts

Shell variables tend to be used within shell scripts rather than at the shell prompt. Consequently, we will look at a few basic examples of shell scripts that make use of shell variables.

A shell script is simply a file that contains a number of UNIX commands. The shell executes the commands in order. Once we have created a shell script, if we give it execute permissions (see Chapter 4, "Permissions and All That") we can run it in the same way we run UNIX commands:

 $ cat script1.sh day=Monday date="15/04/2002" echo The date is $day the $date $ ./script1.sh The date is Monday the 15/04/2002 $ 

We put "./" in front of the script so that the shell knows that it is in our current directory. The shell can only run a command if it knows where it is (we will look at how this is dealt with later in the chapter).

This is very simple and only useful on Monday, April 15, 2002. It would be better if the user could supply the day and date to the script each time it ran. There are two ways of doing this: Either the script asks the user for the information or the user supplies the information on the command line when the script is executed.

We will look at how to do the former first:

 $ cat script2.sh echo what day of the week is it? read day echo what is the date? read date echo The date is $day the $date $ ./script2.sh what day of the week is it? Tuesday what is the date? 16/04/2002 The date is Tuesday the 16/04/2002 $ 

The read command is used to read input from the keyboard and store it in the variable that follows it.

The second way of writing this script makes use of positional parameters.

Positional Parameters

Positional parameters are used in most UNIX commands and consist of everything you type on the command line following the program name:

 $ cat script3.sh echo The date is $1 the $2 $ ./scripts3.sh Wednesday 17/04/2002 The date is Wednesday the 17/04/2002 $ 

This example is much shorter and makes use of some special shell variables that are used to handle positional parameters. Whenever a shell script is called, any parameters supplied on the command line are placed in these special variables (this also explains why we are not allowed to create our own variables beginning with a number). If there were more than nine parameters we would have a problem. For example, $10 would be treated by the shell as the variable $1 followed by a zero; we would need to use curly braces so the shell is sure what we mean. In fact, it is good practice to use curly braces with all shell variables.

As well as creating the variables to hold the positional parameters (${1}, etc.), the shell will also put the name of the shell script in the variable ${0}, the number of parameters in the variable ${#}, and the complete list of parameters in the variable ${*}.

 $ cat script4.sh echo this script is called ${0} echo it was called with ${#} parameters echo the parameters are ${*} $ ./script4.sh one two three four five this script is called ./script4.sh it was called with 4 parameters the parameters are one two three four $ 

We can see if our current shell was called with any parameters by looking at these variables at the shell prompt:

 $ echo ${0} -ksh $ echo ${#} 0 $ echo ${*} $ 

We can see that it wasn't, but we can assign positional parameters using the set command:

 $ set one two three $ echo ${#} 3 $ echo ${*} one two three $ 

The shell was not supplied with these parameters when it was executed, but we have assigned them ourselves. This can be done within shell scripts, also.

Scope of Shell Variables

When a shell variable is created it can only be used within that shell. If you run a subshell the variable will effectively disappear, but when you return to your parent shell it will be available for use again. This means that if you create a variable in a subshell with the same name as one in the parent shell, you will not affect the contents of the variable in the parent shell at all:

 $ name=fred $ echo ${name} fred $ sh $ echo ${name} $ exit $ echo ${name} fred $ 

If we want to see a variable created in a parent shell in its subshell, we can do so by exporting the variable:

 $ name=fred $ export name $ sh $ echo ${name} fred $ name=bill $ echo ${name} bill $ exit $ echo ${name} fred $ 

Now that we have exported the variable it can be seen and used in the subshell, but if we alter the value within the subshell we still cannot affect the value it had in the parent shell.

Exported variables have a special function within the shell; they are used to define the user's environment.

The Environment

A user's environment can be thought of as providing a similar function to user preference settings found within many PC Windows applications. Instead of these preference settings being entered using a nice graphical tool, they are set by assigning environment variables (this is UNIX, remember). An environment variable is simply a shell variable that has been exported. To help differentiate between shell variables and environment variables, the convention is to use lowercase letters for shell variables and uppercase for environment variables (though this is not enforced in any way). The system administrator will set up some of these environment variables for all users, but users may also set their own. In general, if you have access to a shell prompt you can change any aspect of the environment; however, the system administrator can set any of them to read-only to prevent you from doing so.

A number of environment variables are predefined when a user logs in, but the system administrator may define others.

Table 5.1 describes the major environment variables used within the Korn Shell.

Table 5.1. Environment Variables

Variable Name

Description

LOGNAME

This variable holds your login name.

TERM

This variable is used to tell applications and programs what kind of terminal or terminal emulator you are using. If you don't set this to the right value, programs such as vi will not function correctly.

TERMINAL_EMULATOR

An alternative to $TERM. Used by some applications instead of $TERM.

HOME

This holds the full path of the user's home directory and is set at login time.

MAIL

This variable holds the full path of the user's mail file.

MAILCHECK

This variable holds the number of seconds used as the interval between the shell checking the mail file for new mail (usually set to 600).

MAILMSG

This holds the message you would like displayed when you have new mail.

SHELL

This holds the full path to the shell you are using.

PATH

This is set to a colon-separated list of directories that the shell will search to run the commands you type in. If you don't have a PATH set, the only commands you can run are those that are built into the shell!

CDPATH

This is similar to the PATH variable in that it is set to a colon-separated list of directories, but it is used by the cd command to decide what directory to change to. It is not normally set by default.

MANPATH

This can also hold a colon-separated list of directories that the man command will look in for man pages.

LIBPATH

If this variable is set it will be used by C compilers to search for libraries with which to link your code.

TZ

This holds the time zone to use (e.g., GB).

LANG

This holds the language you are using (e.g., en_GB.ISO8859-15).

PS1

This variable holds your primary prompt. The default value is "$ " (a dollar sign followed by a space) for ordinary users and "# " for the root user. This can be changed, and often is.

PS2

The secondary prompt. The shell displays this if it decides that you haven't completed the previous command. The default value is "> ".

PS3

The default value is "#? ". This prompt is displayed when using the ksh select statement interactively.

PS4

The default value is "+ ". This is displayed when using the "-x" option to trace/debug a ksh shell script. This prompt is displayed at the beginning of each expanded line.

ENV

This can hold the name of a file that will be executed within the shell each time it is invoked (unlike .profile which is only invoked at login time).

TMOUT

If this is set to a value greater than zero, the shell will exit (thus logging you off) if a command is not entered within that number of seconds following the issuing of the PS1 prompt.

PWD

The shell sets this variable to hold your current directory. It is updated every time you use the cd command.

IFS

This variable (Internal Field Separator) is set, by default, to a space, a tab, and a newline character. The shell will treat all IFS characters as separators.

FCEDIT

This should be set to the name of the editor you wish to use when running the fc command (which allows you to edit your command history).

DISPLAY

If you are using X Windows to access a server running Solaris, this variable will hold the IP address of your PC or X Station. The address will end in ":0" or ":0.0" to signify that you are using the first screen at that address.

$?

Read-only. Holds the exit status of the last command executed by the shell.

$$

Read-only. Holds the process ID of the current process.

$0

Read-only. Holds the name of the currently executing program.

$@

Read-only. Holds a space-separated list of all the parameters supplied to the current program.

$*

Read-only. Holds all the parameters (as per $@), but when quoted they are separated by the first character of $IFS.

$#

Read-only. Holds the number of parameters supplied to the current program.

$1, $2, $3 etc.

Read-only. Each variable holds the corresponding parameter supplied to the current program. The Korn Shell can handle a large number of positional parameters, but to handle more than nine you must use curly braces (e.g., ${256}).

(Note: The shell will supply default values to PATH, PS1, PS2, PS3, PS4, MAILCHECK, FCEDIT, TMOUT, and IFS. The value of HOME is also set, but by the login program, not the shell.)

To view your current environment variables you can use the env command:

 # env HOME=/ HZ=100 LOGNAME=root MAIL=/var/mail/root PATH=/usr/sbin:/usr/bin SHELL=/sbin/sh TERM=vt100 TZ=Europe/Stockholm # 

This displays only the shell variables that have been exported. If you want to see the value of all your shell variables regardless of whether they have been exported or not, you can use set instead of env:

 # set HOME=/ HZ=100 IFS= LOGNAME=root MAIL=/var/mail/root MAILCHECK=600 OPTIND=1 PATH=/usr/sbin:/usr/bin PS1=# PS2=> SHELL=/sbin/sh TERM=vt100 TZ=Europe/Stockholm # 

    Team-Fly    
    Top
     



    Solaris Operating Environment Boot Camp
    Solaris Operating Environment Boot Camp
    ISBN: 0130342874
    EAN: 2147483647
    Year: 2002
    Pages: 301

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net