11.9. Variables

 <  Day Day Up  >  

11.9. Variables

11.9.1 Local Variables

Local variables are given values that are known only to the shell in which they are created. Variable names must begin with an alphabetic or underscore character. The remaining characters can be alphabetic, decimal digits zero to nine, or an underscore character. Any other characters mark the termination of the variable name .

Setting and Referencing Local Variables

When assigning a value to a variable, there can be no whitespace surrounding the equal sign. To set the variable to null, the equal sign is followed by nothing. If more than one word is assigned to a variable, it must be quoted to protect the whitespace; otherwise , the shell prints an error message and the variable is undefined.

If a dollar sign is prepended to the variable name, the value assigned to that variable can be referenced. If other characters are attached to a variable name, curly braces are used to shield the name of the variable from the extra characters.

Example 11.34.
 1   $  state=Cal  $ echo $state  Cal  2   $  name="Peter Piper"  $ echo $name  Peter Piper  3   $  x=  $  echo $x   # Blank line appears when a variable is either unset or set to null  $ 4   $  state=Cal  $  print ${state}ifornia   California  

EXPLANATION

  1. The variable state is assigned the value Cal . When the shell encounters the dollar sign preceding a variable name, it performs variable substitution. The value of the variable is displayed.

  2. The variable name is assigned the value "Peter Piper" . The quotes are needed to hide the whitespace so that the shell will not split the string into separate words when it parses the command line. The value of the variable is displayed.

  3. The variable x is not assigned a value. It will be assigned a null string. The null value, an empty string, is displayed. The same output would be displayed if the variable had not been set at all.

  4. The variable state is assigned the value Cal . The variable is enclosed in curly braces to shield it from the characters that are appended. The value of the variable Cal is displayed with ifornia appended.

The Scope of Local Variables

A local variable is known only to the shell in which it was created. It is not passed on to subshells. The $$ variable is a special variable containing the PID of the current shell.

Example 11.35.
 1   $  echo $$   1313  2   $  round=world  $  echo $round   world  3   $  ksh   # Start a subshell  4   $  echo $$   1326  5   $  echo $round  6   $  exit   # Exits this shell, returns to parent shell  7   $  echo $$   1313  8   $  echo $round   world  

EXPLANATION

  1. The value of the $$ variable evaluates to the PID of the current shell. The PID of this shell is 1313 .

  2. The local variable round is assigned the string value world and the value of the variable is displayed.

  3. A new Korn shell is invoked. This is called a subshell , or child shell .

  4. The PID of this shell is 1326 . The parent shell's PID is 1313 .

  5. The variable round is not defined in this shell.

  6. The exit command terminates this shell and returns to the parent shell. If the ignoreeof option is not set, Ctrl-D will also exit this shell.

  7. The parent shell returns. Its PID is displayed.

  8. The value of the variable is displayed.

Setting Read-Only Variables

A read-only variable cannot be redefined or unset. It can be set with the readonly or typeset “r built-in commands. You may want to set variables to readonly for security reasons when running in privileged mode.

Example 11.36.
 1   $  readonly name=Tom  $  print $name   Tom  2   $  unset name   ksh: name: is read only  3   $  name=Joe   ksh name: is read only  4   $  typeset -r PATH  $  PATH=${PATH}:/usr/local/bin   ksh: PATH: is read only  

EXPLANATION

  1. The readonly local variable name is assigned the value Tom .

  2. A readonly variable cannot be unset.

  3. A readonly variable cannot be redefined.

  4. The PATH variable is set to be readonly . Any effort to unset or change the variable will produce an error message.

11.9.2 Environment Variables

Environment variables are available to the shell in which they are created and any subshells or processes spawned from that shell. By convention, environment variables are capitalized.

The shell in which a variable is created is called the parent shell . If a new shell is started from the parent shell, it is called the child shell . Some of the environment variables, such as HOME , LOGNAME , PATH , and SHELL , are set before you log in by the /bin/login program. Normally, environment variables are set in the .profile file in the user 's home directory.

Setting Environment Variables

To set environment variables, the export command is used either after assigning a value or when the variable is set. All variables in a script can be exported by turning on the allexport option to the set command (e.g., set -o allexport ).

Example 11.37.
 1   $  TERM=wyse ; export TERM  2   $  export NAME ="John Smith"  $  print $NAME   John Smith  3   $  print $$   319  4   $  ksh  5   $  print $$   340  6   $  print $NAME   John Smith  7   $  NAME="April Jenner"  $  print $NAME   April Jenner  8   $  exit  9   $  print $$   319  10  $  print $NAME   John Smith  

EXPLANATION

  1. The TERM variable is assigned wyse . The variable is exported. Now processes started from this shell will inherit the variable.

  2. The variable is exported and defined in the same step. (New with the Korn shell.)

  3. The value of this shell's PID is printed.

  4. A new Korn shell is started. The new shell is the child ; the original shell is its parent .

  5. The PID of the new Korn shell, stored in the $$ ( 340 ) variable, is printed.

  6. The variable was exported to the new shell and is displayed.

  7. The variable is reset to April Jenner and displayed.

  8. This Korn child shell is exited. The parent shell will return.

  9. The PID of the parent, 319 , is displayed again.

  10. The variable NAME contains its original value. Variables retain their values when exported from parent to child. The child cannot change the value of a variable for its parent.

Special Environment Variables

The Korn shell assigns default values to the environment variables, PATH , PS1 , PS2 , PS3 , PS4 , MAILCHECK , FCEDIT , TMOUT , and IFS . The SHELL , LOGNAME , USER , and HOME are set by the /bin/login program. You can change the values of the defaults and set the others listed in Table 11.9.

Table 11.9. Korn Shell Environment Variables

Variable Name

Meaning

_ (underscore)

The last argument of the previous command.

CDPATH

The search path for the cd command. A colon -separated list of directories used to find a directory if the / , ./ , or ../ is not at the beginning of the pathname.

COLUMNS

If set, defines the width of the edit window for shell edit modes and the select command.

EDITOR

Pathname for a built-in editor: emacs , gmacs , or vi .

ENV

A variable set to the name of a file, containing functions and aliases, that the Korn shell will invoke when the ksh program is invoked. On versions newer than 1988, this file is only executed when ksh is invoked interactively, not for noninteractive shells . The variable is not expanded if the privileged option is turned on.

ERRNO

System error number. Its value is the error number of the most recently failed system call.

FCEDIT

Default editor name for the fc command. On versions newer than 1988, this variable is called HISTEDIT , and the fc command is hist .

FPATH

A colon-separated list of directories that defines the search path for directories containing auto-loaded functions.

HISTEDIT

For versions of the Korn shell newer than 1988, the new name for FCEDIT .

HISTFILE

Specifies file in which to store command history.

HISTSIZE

Maximum number of commands from the history that can be accessed; default is 128.

HOME

Home directory; used by cd when no directory is specified.

IFS

Internal field separators, normally space, tab, and newline, used for field splitting of words resulting from command substitution, lists in loop constructs, and reading input.

LINENO

Current line number in script.

LINES

Used in select loops for vertically displaying menu items; default is 24.

MAIL

If this parameter is set to the name of a mail file and the MAILPATH parameter is not set, the shell informs the user of the arrival of mail in the specified file.

MAILCHECK

This parameter specifies how often (in seconds) the shell will check for the arrival of mail in the files specified by the MAILPATH or MAIL parameters. The default value is 600 seconds (10 minutes). If set to zero, the shell will check before issuing each primary prompt.

MAILPATH

A colon-separated list of filenames. If this parameter is set, the shell informs the user of the arrival of mail in any of the specified files. Each filename can be followed by a % and a message that will be printed when the modification time changes. The default message is You have mail .

OLDPWD

Last working directory.

PATH

The search path for commands; a colon-separated list of directories the shell uses to search for the command you want to execute.

PWD

Present working directory; set by cd .

PPID

Process ID of the parent process.

PS1

Primary prompt string, by default $ .

PS2

Secondary prompt string, by default > .

PS3

Selection prompt string used with the select command, by default #? .

PS4

Debug prompt string used when tracing is turned on, by default + .

RANDOM

Random number generated each time the variable is referenced.

REPLY

Set when read is not supplied arguments.

SHELL

When the shell is invoked, it scans the environment for this name. The shell gives default values to PATH , PS1 , PS2 , MAILCHECK , and IFS . HOME and MAIL are set by login .

TMOUT

Specifies number of seconds to wait for input before exiting.

VISUAL

Specifies editor for in-line command editing: emacs , gmacs , or vi .


11.9.3 Listing Set Variables

There are three built-in commands that print the value of variables: set , env , and typeset . The set command prints all variables, local and global. The env command prints only global variables. The typeset command prints all variables, integers, functions, and exported variables. The set “o command prints all options set for the Korn shell.

Example 11.38.
 1   $  env   # Partial list   LOGNAME=ellie   TERMCAP=suncmd:te=\E[>4h:ti=\E[>4l:tc=sun:   USER=ellie   DISPLAY=:0.0   SHELL=/bin/ksh   HOME=/home/jody/ellie   TERM=suncmd   LD_LIBRARY_PATH=/usr/local/OW3/lib   PWD=/home/jody/ellie/perl  2   $  typeset   export MANPATH   export PATH   integer ERRNO   export FONTPATH   integer OPTIND   function LINENO   export OPENWINHOME   export LOGNAME   function SECONDS   integer PPID   PS3   PS2   export TERMCAP   OPTARG   export USER   export DISPLAY   function RANDOM   export SHELL   integer TMOUT   integer MAILCHECK  3   $  set   DISPLAY=:0.0   ERRNO=10   FCEDIT=/bin/ed   FMHOME=/usr/local/Frame2.1X   FONTPATH=/usr/local/OW3/lib/fonts   HELPPATH=/usr/local/OW3/lib/locale:/usr/local/OW3/lib/help   HOME=/home/jody/ellie   IFS=   LD_LIBRARY_PATH=/usr/local/OW3/lib   LINENO=1   LOGNAME=ellie   MAILCHECK=600   MANPATH=/usr/local/OW3/share/man:/usr/local/OW3/man:/   usr/local/man:/usr/local/doctools/man:/usr/man   OPTIND=1   PATH=/home/jody/ellie:/usr/local/OW3/bin:/usr/ucb:/   usr/local/doctools/bin:/usr/bin:/usr/local:/usr/etc:/etc:/   usr/spool/news/bin:/home/jody/ellie/bin:/usr/lo   PID=1332   PS1=$   PS2=>   PS3=#?   PS4=+   PWD=/home/jody/ellie/kshprog/joke   RANDOM=4251   SECONDS=36   SHELL=/bin/ksh   TERM=suncmd   TERMCAP=suncmd:te=\E[>4h:ti=\E[>4l:tc=sun:   TMOUT=0   USER=ellie   _=pwd   name=Joe   place=San Francisco   x=  4  set -o   allexport      off   bgnice        on   emacs         off   errexit       off   gmacs         off   ignoreeof     off   interactive   on   keyword       off   markdirs      off   monitor       on   noexec        off   noclobber     off   noglob        off   nolog         off   nounset       off   privileged    off   restricted    off   trackall      off   verbose       off   viraw         off   xtrace        off  

EXPLANATION

  1. The env command lists all environment (exported) variables. These variables are, by convention, named with uppercase letters . They are passed from the process in which they are created to any of the child processes.

  2. The typeset command displays all variables and their attributes, functions, and integers. The typeset command with the + option displays only the names of the variables.

  3. The set command, without options, prints all set variables, local and exported, including variables set to null.

  4. The set command with the “o option lists all built-in variables that are set to on or off. To turn options off, use the plus sign ( + ), and to turn options on, use the minus sign ( ); for example, set “o allexport turns on the allexport option, causing all variables to be set as global.

11.9.4 Unsetting Variables

Both local and environment variables can be unset by using the unset command (unless the variables are set to readonly ).

Example 11.39.
  unset name; unset TERM  

EXPLANATION

The variables name and TERM are no longer defined for this shell.

11.9.5 Printing the Values of Variables

The echo command (used in Bourne and C shells) is still effective in this shell, but the print command has more options and is more efficient. Both the echo command and print command are built into the shell. The print command has a number of options to control its output. They are listed in Table 11.10.

Table 11.10. print Options

Option

Meaning

Any arguments that follow are not print options. The dash allows arguments that contain a hyphen, for example, “2 .

“f

For versions newer than 1988, used to emulate printf .

“n

No newline in output; like echo “n .

“p

Sends output to a coprocess or pipe (&) rather than to standard output.

“r

Prevents the print command from interpreting escape sequences.

“R

Prevents ksh from treating a “2 or “x as a print argument; turns off the dash if preceding an argument (except “n ); \t , \c , \c are not recognized as special and appear unchanged when printed without the \ .

“s

Output is appended to the history file as a command rather than to standard output.

“un

Redirects output to file descriptor n .


Example 11.40.
 1   $  print Hello my friend and neighbor!   Hello my friend and neighbor!  2   $  print "Hello       friends"   Hello       friends  3   $  print r "\n"   \n  4   $  print -s "date +%H"  $  history -2   132 print -s "date +%H"   133 date +%H   134 history -2  $  r 133   09  5   $  print n $HOME   /home/jody/ellie  6   $  var=world  $  print ${var}wide   worldwide  7   $  print x is an option   ksh: print: bad option(s)  8   $  print   x is an option   x is an option  

EXPLANATION

  1. The shell parses the command line, breaks the command line into words (tokens) separated by space, and passes the words as arguments to the print command. The shell removes all the extra whitespace between words.

  2. The quotes create a single string. The shell evaluates the string as a single word and the whitespace is preserved.

  3. This is the raw option. Any escape sequences, such as \r , are not interpreted.

  4. The “s option appends the print command's arguments to the history file as a command. The string "date +%H" is the argument to the print command. The date string is appended to the history list as a command and then executed with the r command (history's redo command).

  5. The “n option suppresses the newline. The Korn shell prompt is on the same line as the output from the print command.

  6. The local variable is assigned the value world . The braces insulate the variable from characters appended to it.

  7. When the first argument to the print function begins with a dash, the print command interprets the argument as one of its options, unless an additional preceding dash is provided.

  8. The dash as an option allows you to use a dash as the first character in the string to be printed.

11.9.6 Escape Sequences

Escape sequences consist of a character preceded by a backslash and have a special meaning when enclosed within quotes. (See Table 11.11.)

Table 11.11. Escape Sequences

Backslash Character

Meaning

\a

Bell character

\b

Backspace

\c

Suppress newline and ignore any arguments that follow \c

\f

Formfeed

\n

Newline

\r

Return

\t

Tab

\v

Vertical tab

\\

Backslash

\0x

Eight-bit character with a 1-, 2-, or 3-digit ASCII value, as in print \0124

\E

Only on versions newer than 1988; used for an escape sequence


The print command, without the “r and “R options, formats output when any of the following escape sequences are placed within a string. The string must be enclosed in double or single quotes.

Example 11.41.
 1   $  print '\t\t\tHello\n'   Hello  $ 2   $  print "\aTea \tTime!\n\n"   Ding (bell rings) Tea       Time!  

EXPLANATION

  1. The backslash characters must be quoted with either single or double quotes. The \t escape sequence represents a tab, and \n represents a newline. The output is three tabs, followed by the string Hello , and a newline.

  2. The \a escape sequence causes a bell to ring (\07) and the \t creates a tab. The two \n sequences will print two newline characters.

11.9.7 Variable Expressions and Expansion Modifiers

Variable expressions can be tested and modified by using special modifiers. The modifier provides a shortcut conditional test to check whether a variable has been set, and then, depending on the modifier, may assign a default value to the variable. These expressions can be used with conditional constructs such as if and elif . See Table 11.12.

Table 11.12. Variable Expressions and Modifiers

Expression

Function

${variable: “word}

If variable is set and is nonnull, substitute its value; otherwise, substitute word .

${variable:=word}

If variable is not set or is null, set it to word ; the value of variable is substituted permanently. Positional parameters may not be assigned in this way.

${variable:+word}

If variable is set and is nonnull, substitute word; otherwise substitute nothing.

${variable:?word}

If variable is set and is nonnull, substitute its value; otherwise, print word and exit from the shell. If word is omitted, the message parameter null or not set is printed.


The colon does not have to be used with the modifier. Using the colon with the modifier checks whether the variable is not set or is null; without the colon, a variable set to null is considered a set variable.

Example 11.42.
 (Using Temporary Default Values) 1   $  fruit  =  peach  2   $  print ${fruit:plum}   peach  3   $  print ${newfruit:apple}   apple  4   $  print $newfruit  5   $  print ${TERM:-vt120}   sun-cmd  

EXPLANATION

  1. The variable fruit is assigned the value peach .

  2. The special modifier will check to see if the variable fruit has been set. If it has, the value peach is printed; if not, plum is printed.

  3. The variable newfruit has not been set. The value apple will be printed.

  4. The variable newfruit was not set, so nothing prints. In step 3, the expression was simply replaced with the word apple and printed.

  5. If the TERM variable has not been set, a default value vt120 will be displayed. In this example, the terminal has already been set to sun “cmd , a Sun workstation.

Example 11.43.
 (Assigning Permanent Default Values) 1   $  name=  2   $  print ${name:=Patty}   Patty  3   $  print $name   Patty  4   $  print ${TERM:=vt120}   vt120  $  print $TERM   vt120  

EXPLANATION

  1. The variable name is assigned the value null .

  2. The special modifier := will check to see if the variable name has been set to some value other than null. If it has been set, it will not be changed; if it is either null or not set, it will be assigned the value to the right of the equal sign. Patty is assigned to name because the variable is set to null. The setting is permanent.

  3. The variable name still contains the value Patty .

  4. If the variable TERM is not set, it will be assigned the default value vt120 permanently.

Example 11.44.
 (Assigning Temporary Alternate Value) 1   $  foo=grapes  2   $  print ${foo:+pears}   pears  $  print $foo   grapes  

EXPLANATION

  1. The variable foo has been assigned the value grapes .

  2. The special modifier :+ will check to see if the variable has been set. If it has been set, it will temporarily be reset to grapes . If it has not been set, null is returned.

Example 11.45.
 (Creating Error Messages Based on Default Values) 1   $  print ${namex:?"namex is undefined"}   ksh: namex: namex is undefined  2   $  print ${y?}   ksh: y: parameter null or not set  

EXPLANATION

  1. The :? modifier will check to see if the variable has been set. If not, the string to the right of the ? is printed to standard error, after the name of the variable. If in a script, the script exits.

  2. If a message is not provided after the ? , the Korn shell sends a default message to standard error. Without the colon, the ? modifier would consider a variable set to null a set variable, and the message would not be printed.

Example 11.46.
 (Line from a System Script)  if [ "${uid:=0}" -ne 0 ]  

EXPLANATION

If the UID (user ID) has a value, it will not be changed; if it does not have a value, it will be assigned the value zero (superuser). The value of the variable will be tested for nonzero. This line was taken from the /etc/shutdown program (SVR4/Solaris 2.5). It is here to give you an example of how variable modifiers are used.

11.9.8 Variable Expansion of Substrings

Pattern-matching arguments are used to strip off certain portions of a string from either the front or end of the string. The most common use for these operators is stripping off pathname elements from the head or tail of the path. See Table 11.13.

Table 11.13. Variable Expansion Substrings

Expression

Function

${variable%pattern}

Matches the smallest trailing portion of the value of variable to pattern and removes it.

${variable%%pattern}

Matches the largest trailing portion of the value of variable to pattern and removes it.

${variable#pattern}

Matches the smallest leading portion of the value of variable to pattern and removes it.

${variable##pattern}

Matches the largest leading portion of the value of variable to pattern and removes it.


Example 11.47.
 1   $  pathname="/usr/bin/local/bin"  2   $  print ${pathname%/bin*}   /usr/bin/local  

EXPLANATION

  1. The local variable pathname is assigned /usr/bin/local/bin .

  2. The % removes the smallest trailing portion of pathname containing the pattern /bin , followed by zero or more characters; that is, it strips off /bin .

Example 11.48.
 1   $  pathname="usr/bin/local/bin"  2   $  print ${pathname%%/bin*}   /usr  

EXPLANATION

  1. The local variable pathname is assigned /usr/bin/local/bin .

  2. The %% removes the largest trailing portion of pathname containing the pattern /bin , followed by zero or more characters; that is, it strips off /bin/local/bin .

Example 11.49.
 1   $  pathname=/home/lilliput/jake/.cshrc  2   $  print ${pathname#/home}   /lilliput/jake/.cshrc  

EXPLANATION

  1. The local variable pathname is assigned /home/liliput/jake/.cshrc .

  2. The # removes the smallest leading portion of pathname containing the pattern /home ; that is, /home is stripped from the beginning of the path variable.

Example 11.50.
 1   $  pathname=/home/liliput/jake/.cshrc  2   $  print ${pathname##*/  }  .cshrc  

EXPLANATION

  1. The local variable pathname is assigned /home/liliput/jake/.cshrc .

  2. The ## removes the largest leading portion of pathname containing zero or more characters up to and including the last slash; that is, it strips off /home/lilliput/jake/ from the path variable.

11.9.9 Variable Attributes: The typeset Command

The attributes of a variable, such as its case, width, and left or right justification, can be controlled by the typeset command. When the typeset command changes the attributes of a variable, the change is permanent. The typeset function has a number of other functions. See Table 11.14.

Example 11.51.
 1   $  typeset u name="john doe"  $ print "$name"  JOHN DOE             # Changes all characters to uppercase.  2   $  typeset l name  $ print $name  john doe             # Changes all characters to lowercase.  3   $  typeset L4 name  $ print $name  john                 # Left-justified fixed-width 4-character field.  4   $  typeset R2 name  $ print $name  # Right-justified fixed-width 2-character field.   hn  5   $  name="John Doe"  $  typeset Z15 name   # Nullpadded sting, 15-space field width  $  print "$name"   John Doe  6   $  typeset LZ15 name   # Left-justified, 15-space field width.  $  print "$name$name"   John Doe       John Doe  7   $  integer n=25  $  typeset -Z15 n   # Left-justified, zero-padded integer.  $  print "$n"   000000000000025  8   $  typeset lL1 answer=Yes   # Left justify one lowercase letter.  $ print $answer  y  

Table 11.14. Other Uses of the typeset Command

Command

What It Does

typeset

Displays all variables

typeset “i num

Will only accept integer values for num

typeset “x

Displays exported variables

typeset a b c

If defined in a function, creates a , b , and c to be local variables

typeset “r x=foo

Sets x to foo and then makes it read-only


EXPLANATION

  1. The “u option to the typeset command converts all characters in a variable to uppercase.

  2. The “l option to the typeset command converts all characters in a variable to lowercase.

  3. The “L option to the typeset command converts the variable name to a left-justified, four-character string, john .

  4. The “R option to the typeset command converts the variable name to a right-justified, two-character string, hn .

  5. The variable name is set to John Doe . The “Z option to the typeset command will convert the string to a null-padded, 15-space string. The variable is quoted to preserve whitespace.

  6. The variable name is converted to a left-justified, 15-space, null-padded string.

  7. The variable n is an integer (see typeset “i , Table 11.14) assigned the value 25 . The typeset command will convert the integer n to a zero-filled, 15-space, left-justified number.

  8. The variable answer is assigned the value Yes and converted to a lowercase, left-justified, one-character string. (This can be very useful when handling user input in a script.)

11.9.10 Positional Parameters

Normally, the special built-in variables, often called positional parameters , are used in shell scripts when passing arguments from the command line, or used in functions to hold the value of arguments passed to the function. The variables are called positional parameters because they are referenced by numbers 1, 2, 3, and so on, representing their respective positions in the parameter list. See Table 11.15.

Table 11.15. Positional Parameters

Expression

Function

$0

References the name of the current shell script

$1 “$9

Positional parameters 1 “9

${10}

Positional parameter 10

$#

Evaluates to the number of positional parameters

$*

Evaluates to all the positional parameters

$@

Same as $* , except when double quoted

"$*"

Evaluates to "$1 $2 $3" , and so on

"$@"

Evaluates to "$1" "$2" "$3" , and so on


The name of the shell script is stored in the $0 variable. The positional parameters can be set and reset with the set command.

Example 11.52.
 1   $  set tim bill ann fred  $  print $*   # Prints all the positional parameters.   tim bill ann fred  2   $  print   # Prints the first position.   tim  3   $  print   # Prints the second and third position.   bill ann  4   $  print $#   # Prints the total number of positional parameters.   4  5   $  set a b c d e f g h i j k l m  $  print   # Prints the first positional parameter followed by a 0.   a0  $  print   # Prints the 10th and 11th positions.   j k  6   $  print $#   13  7   $  print $*   a b c d e f g h i j k l m  8   $  set file1 file2 file3  $  print $$#    9   $  eval print $$#   file3  

EXPLANATION

  1. The set command assigns values to positional parameters. The $* special variable contains all of the parameters set.

  2. The value of the first positional parameter, tim , is displayed.

  3. The value of the second and third parameters, bill and ann , are displayed.

  4. The $# special variable contains the number of positional parameters currently set.

  5. The set command resets all of the positional parameters. The original parameter list is cleared. To print any positional parameters beyond 9, the curly braces are used to keep the two digits together. Otherwise, the value of the first positional parameter is printed, followed by the number appended to it.

  6. The number of positional parameters is now 13.

  7. The values of all the positional parameters are printed.

  8. The dollar sign is escaped; $# is the number of arguments. The print command displays $3 , a literal dollar sign followed by the number of positional parameters.

  9. The eval command parses the command line a second time before executing the command. The first time parsed by the shell, the print would display $3 ; the second time, after eval , the print displays the value of $3 , file3 .

11.9.11 Other Special Variables

The Korn shell has some special built-in variables, as shown in Table 11.16.

Table 11.16. Special Variables

Variable

Meaning

$$

PID of the shell

$ “

ksh options currently set

$?

Exit value of last executed command

$!

PID of last job put in background


Example 11.53.
 1   $  print The pid of this shell is $$   The pid of this shell is 4725  2   $  print The options for this korn shell are $   The options for this korn shell are ismh  3   $  grep dodo /etc/passwd  $  print $?   1  4   $  sleep 25&   [1]    400  $  print $!   400  

EXPLANATION

  1. The $$ variable holds the value of the PID for this process.

  2. The $ “ variable lists all options for this interactive Korn shell.

  3. The grep command searches for the string dodo in the /etc/passwd file. The ? variable holds the exit status of the last command executed. Because the value returned from grep is 1, grep is assumed to have failed in its search. An exit status of 0 indicates a successful exit.

  4. The & appended to the sleep command causes the command to be executed in the background. The $! variable holds the PID of the last command placed in the background.

 <  Day Day Up  >  


UNIX Shells by Example
UNIX Shells by Example (4th Edition)
ISBN: 013147572X
EAN: 2147483647
Year: 2004
Pages: 454
Authors: Ellie Quigley

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