Section 7.12. Enhancements


[Page 276 (continued)]

7.12. Enhancements

In addition to the new facilities that have already been described, the Korn shell also offers some enhancements to older shells in the following areas:

  • redirection

  • pipes

  • command substitution

  • variable access

  • extra built-in commands

7.12.1. Redirection

The Korn shell supplies a minor extra redirection facilitythe ability to strip leading tabs off "here" documents. Figure 7-26 gives the augmented syntax.

Figure 7-26. Redirection with a "here" document in the Korn shell.

command << [-] word


If word is preceded by a -, then leading tabs are removed from the lines of input that follow. Here's an example:

$ cat <<- ENDOFTEXT >           this input contains >     some leading tabs >ENDOFTEXT this input contains some leading tabs $ _ 


This allows "here" text in a script to be indented to match the nearby shell commands without affecting how the text is used.


[Page 277]

7.12.2. Pipes

The |& operator supports a simple form of concurrent processing. When a command is followed by |&, it runs as a background process whose standard input and output channels are connected to the original parent shell via a two-way pipe. When the original shell generates output using a print -p command (discussed later in this chapter), it is sent to the child shell's standard input channel. When the original shell reads input using a read -p command (also discussed later in this chapter), it is taken from the child shell's standard output channel. Here's an example:

$ date |&               ...start child process. [1]   8311 $ read -p theDate       ...read from standard output of child. [1] +  Done    date |&     ...child process terminates. $ echo $theDate            ...display the result. Tue May 10 21:36:57 CDT 2005 $ _ 


7.12.3. Command Substitution

In addition to the older method of command substitutionsurrounding the command with grave accentsthe Korn shell also allows you to perform command substitution using the syntax shown in Figure 7-27.

Figure 7-27. Command substitution in the Korn shell.

$( command )


Note that the $ that immediately precedes the open parentheses is part of the syntax, and is not a prompt. Here's an example:

$ echo there are $(who | wc -l) users on the system there are 6 users on the system $ _ 


To substitute the contents of a file into a shell command, you may use $(<file) as a faster form of $(cat file).

7.12.4. Variables

The Korn shell supports the following additional variable facilities:

  • more flexible access methods

  • more predefined local variables

  • more predefined environment variables

  • simple arrays

  • a typeset command for formatting the output of variables

The next few subsections describe each feature.


[Page 278]
7.12.4.1. Flexible Access Methods

In addition to the typical variable access methods, the Korn shell supports some more complex access methods (Figure 7-28).

Figure 7-28. Korn shell variable access methods.

Syntax

Action

${#name}

Replaced by the length of the value of name.

${#name[*] }

Replaced by the number of elements in the array name.

${name:+word }

${name:=word }

${name:?word }

${name:+word }

Work like their counterparts that do not contain a :, except that name must be set and non-null instead of just set.

${name#pattern}

${name##pattern}

Removes a leading pattern from name. The expression is replaced by the value of name if name doesn't begin with pattern, and with the remaining suffix if it does. The first form removes the smallest matching pattern, and the second form removes the largest matching pattern.

${name%pattern}

${name%%pattern}

Removes a trailing pattern from name. The expression is replaced by the value of name if name doesn't end with pattern, and with the remaining prefix if it does. The first form removes the smallest matching pattern, and the second form removes the largest matching pattern.


Here are some examples of these features:

$ fish='smoked salmon'       ...set a variable. $ echo ${#fish}     ...display the length of the value. 13 $ cd dir1                    ...move to directory. $ echo $PWD    ...display the current working directory. /home/glass/dir1 $ echo $HOME /home/glass $ echo ${PWD#$HOME/}         ...remove leading $HOME/ dir1 $ fileName=menu.ksh          ...set a variable. $ echo ${fileName%.ksh}.bak  ...remove trailing ".ksh" menu.bak                     ...and add ".bak". $ _ 


7.12.4.2. Predefined Local Variables

In addition to the common predefined local variables, the Korn shell supports those listed in Figure 7-29.


[Page 279]

Figure 7-29. Korn shell predefined local variables.

Name

Value

$_

The last parameter of the previous command.

$PPID

The process ID number of the shell's parent.

$PWD

The current working directory of the shell.

$OLDPWD

The previous working directory of the shell.

$RANDOM

A random integer.

$REPLY

Set by a select command.

$SECONDS

The number of seconds since the shell was invoked.

$CDPATH

Used by the cd command.

$COLUMNS

Sets the width of the edit window for the built-in editors.

$EDITOR

Selects the built-in editor type.

$ENV

Selects the name of the Korn shell startup file.

$FCEDIT

Defines the editor that is invoked by the fc command.

$HISTFILE

The name of the history file.

$HISTSIZE

The number of history lines to remember.

$LINES

Used by select to determine how to display the selections.

$MAILCHECK

Tells the shell how many seconds to wait between mail checks. The default value is 600.

$MAILPATH

This should be set to a list of filenames, separated by colons. The shell checks these files for modification every $MAILCHECK seconds.

$PS3

The prompt used by the select command, #? by default.

$TMOUT

If set to a number greater than zero and more than $TMOUT seconds elapse between commands, the shell terminates.

$VISUAL

Selects the built-in editor type.


Here are some examples of these predefined variables:

$ echo hi there   ...display a message to demonstrate $_. hi there $ echo $_         ...display last arg of last command. 
[Page 280]
there $ echo $PWD ...display the current working dir. /home/glass $ echo $PPID ...display the shell's parent pid. 27709 $ cd / ...move to the root directory. $ echo $OLDPWD ...display last working directory. /home/glass $ echo $PWD ...display current working directory. / $ echo $RANDOM $RANDOM ...display two random numbers. 32561 8323 $ echo $SECONDS ...display seconds since shell began. 918 $ echo $TMOUT ...display the timeout value. 0 ...no timeout selected. $ _


7.12.4.3. One-Dimensional Arrays

The Korn shell supports simple one-dimensional arrays. To create an array, simply assign a value to a variable name using a subscript between 0 and 511 in brackets. Array elements are created as needed. The syntax is given in Figure 7-30.

Figure 7-30. Korn shell array definition and use.

To set the value of an array element:

name[subscript]=value


To access the value of an array element:

${name[subscript]}



If you omit subscript, the value of 0 is used by default. Here's an example that uses a script to display the squares of the numbers between 0 and 9:

$ cat squares.ksh                   ...list the script. i=0 while (( i < 10 )) do  (( squares[$i] = i * i ))  ...assign individual element.  (( i = i + 1 ))            ...increment loop counter. done echo 5 squared is ${squares[5]}  ...display one element. 
[Page 281]
echo list of all squares is ${squares[*]} ...display all. $ ksh squares.ksh ...execute the script. 5 squared is 25 list of all squares is 0 1 4 9 16 25 36 49 64 81 $ _


7.12.4.4. Typeset

Figure 7-31 describes the typeset shell command.

Figure 7-31. Description of the typeset shell command.

Shell Command: typeset { - HLRZfilrtux [value] [name [ =word ]]}*

typeset allows the creation and manipulation of variables. It allows variables to be formatted, converted to an internal integer representation for speedier arithmetic, made read-only, made exportable, and switched between lowercase and uppercase.

Every variable has an associated set of flags that determine its properties. For example, if a variable has its "uppercase" flag set, it will always map its contents to uppercase, even when they are changed. The options to typeset operate by setting and resetting the various flags associated with named variables. When an option is preceded by -, it causes the appropriate flag to be turned on. To turn a flag off and reverse the sense of the option, precede the option by a + instead of a -.


There now follows a list of the options to typeset with illustrations of their usage. I've split the descriptions up into related sections to make things a little easier.

Formatting

In all of the formatting options, the field width of name is set to value if present; otherwise, it is set to the width of word (Figure 7-32).

Figure 7-32. Formatting with the typeset shell command.

Option

Meaning

L

Turn the L flag on and turn the R flag off. Left justify word and remove leading spaces. If the width of word is less than name's field width, then pad it with trailing spaces. If the width of word is greater than name's field width, then truncate its end to fit. If the Z flag is set, leading zeroes are also removed.

R

Turn the R flag on and turn the L flag off. Right justify word and remove trailing spaces. If the width of word is less than name's field width, then pad it with leading spaces. If the width of word is greater than name's field width, then truncate its end to fit.

Z

Right justify word and pad with zeroes if the first nonspace character is a digit and the L flag is off.



[Page 282]
Case

With the case options (Figure 7-33), the value can be converted to upper or lower case.

Figure 7-33. Changing the case of characters with the typeset shell command.

Option

Meaning

l

Turn the l flag on and turn the u flag off. Convert word to lowercase.

u

Turn the u flag on and turn the l flag off. Convert word to uppercase.


Here's an example that left justifies all the elements in an array and then displays them in uppercase:

$ cat justify.ksh         ...list the script. wordList[0]='jeff'     # set three elements. wordList[1]='john' wordList[2]='ellen' typeset -uL7 wordList  # typeset all elements in array. echo ${wordList[*]}    # beware! shell removes nonquoted spaces echo "${wordList[*]}"  # works OK. $ ksh justify.ksh         ...execute the script. JEFF JOHN ELLEN JEFF    JOHN    ELLEN $ _ 


Miscellaneous

Figure 7-34 shows miscellaneous typeset shell command options.

Figure 7-34. Miscellaneous typeset shell command options.

Option

Meaning

f

The only flags that are allowed in conjunction with this option are t, which sets the trace option for the named functions, and x, which displays all functions with the x attribute set.

t

Tags name with the token word.


In the following example, I selected the function factorial () to be traced using the -ft option, and then ran the script:

$ cat func5.ksh         ...list the script. factorial ()           # one-parameter function {  if (( $1 <= 1 )) 
[Page 283]
then return 1 else typeset tmp typeset result (( tmp = $1 - 1 )) factorial $tmp (( result = $? * $1 )) return $result fi } # typeset -ft factorial ...select a function trace. factorial 3 echo factorial 3 = $? $ ksh func5.ksh ...execute the script. + let 3 <= 1 ...debugging information. + typeset tmp + typeset result + let tmp = 3 - 1 + factorial 2 + let 2 <= 1 + typeset tmp + typeset result + let tmp = 2 - 1 + factorial 1 + let 1 <= 1 + return 1 + let result = 1 * 2 + return 2 + let result = 2 * 3 + return 6 factorial 3 = 6 $ _


7.12.4.5. Typeset With No Named Variables

If no variables are named, then the names of all the parameters that have the specified flags set are listed. If no flags are specified, then all the parameters and their flag settings are listed. Here's an example:

$ typeset     ...display a list of all typeset variables. export NODEID export PATH ... leftjust 7 t export integer MAILCHECK $ typeset -i   ...display list of integer typeset vars. 
[Page 284]
LINENO=1 MAILCHECK=60 ... $ _


7.12.5. Built-Ins

The Korn shell includes the following built-in commands:

  • cd

  • set

  • print (an enhancement of the echo command)

  • read

  • test

  • trap

The next few subsections contain a description of each built-in.

7.12.5.1. Cd

The Korn shell's version of cd supports several new features (Figure 7-35).

Figure 7-35. Description of the cd shell command.

Shell Command: cd { name }

cd oldName newName

The first form of the cd command is processed as follows:

  • If name is omitted, the shell moves to the home directory specified by $HOME.

  • If name is equal to -, the shell moves to the previous working directory that is kept in $OLDPWD.

  • If name begins with a /, the shell moves to the directory whose full name is name.

  • If name begins with anything else, the shell searches through the directory sequence specified by $CDPATH for a match, and moves the shell to the matching directory. The default value of $CDPATH is null, which causes cd to search only the current directory.

If the second form of cd is used, the shell replaces the first occurrence of the token oldName by the token newName in the current directory's full pathname, and then attempts to change to the new pathname. The shell always stores the full pathname of the current directory in the variable PWD. The current value of $PWD may be displayed by using the built-in command pwd.


Here's an example of cd in action:

$ CDPATH=.:/usr  ...set my CDPATH. $ cd dir1        ...move to "dir1", located under ".". 
[Page 285]
$ pwd /home/glass/dir1 $ cd include ...move to "include", located in "/usr". $ pwd ...display the current working dir. /usr/include $ cd - ...move to my previous directory. $ pwd ...display the current working dir. /home/glass/dir1 $ _


7.12.5.2. Set

The set command (Figure 7-36) allows you to set and unset flags that control shellwide characteristics.

Figure 7-36. Description of the set shell command.

Shell Command: set [ +-aefhkmnostuvx ] [ +-o option ] { arg } *

The Korn shell version of set supports all of the Bourne set features plus a few more. The various features of set do not fall naturally into categories, so I'll just list each one together with a brief description. An option preceded by a + instead of a - reverses the sense of the description.


Figure 7-37 is a list of the options to set.

Figure 7-37. set shell command options

[Page 286]

Option

Meaning

a

All variables that are created are automatically flagged for export.

f

Disable filename substitution.

h

All non-built-in commands are automatically flagged as tracked aliases.

m

Place all background jobs in their own unique process group and display notification of completion. This flag is automatically set for interactive shells.

n

Accept but do not execute commands. This flag has no effect on interactive shells.

o

This option is described separately below.

p

Set $PATH to its default value, cause the startup sequence to ignore the $HOME/.profile file and read "/etc/suid_profile" instead of the $ENV file. This flag is set automatically whenever a shell is executed by a process in "set user ID" or "set group ID" mode. For more information on "set user ID" processes, consult Chapter 12, "Systems Programming."

s

Sort the positional parameters.

--

Do not change any flags. If no arguments follow, all of the positional parameters are unset.



[Page 286]
7.12.5.3. The -o Option

The -o option of set takes an argument. The argument frequently has the same effect as one of the other flags to set. If no argument is supplied, the current settings are displayed. Figure 7-38 is a list of the valid arguments and their meanings.

Figure 7-38. set -o arguments.

[Page 287]

Option

Meaning

allexport

Equivalent to the a flag.

errexit

Equivalent to the e flag.

bgnice

Background processes are executed at a lower priority.

emacs

Invokes the built-in emacs editor.

gmacs

Invokes the built-in gmacs editor.

ignoreeof

Don't exit on Control-D. exit must be used instead.

keyword

Equivalent to the k flag.

markdirs

Append trailing / to directories generated by filename substitution.

monitor

Equivalent to the m flag.

noclobber

Prevents redirection from truncating existing files.

noexec

Equivalent to the n flag.

noglob

Equivalent to the f flag.

nolog

Do not save function definitions in history file.

nounset

Equivalent to the u flag.

privileged

Same as -p.

verbose

Equivalent to the v flag.

trackall

Equivalent to the h flag.

vi

Invokes the built-in vi editor.

viraw

Characters are processed as they are typed in vi mode.

xtrace

Equivalent to the x flag.


I can set the ignoreeof option in my ".profile" script to protect myself against accidental Control-D logouts like this:

set -o ignoreeof


7.12.5.4. print

The print command is a more sophisticated version of echo, and allows you to send output to a arbitrary file descriptor. Figure 7-39 describes how it works.

Figure 7-39. Description of the print shell command.
(This item is displayed on page 287 in the print version)

Shell Command: print -npsuR [n] { arg }*

By default, print displays its arguments to standard output, followed by a newline. The -n option inhibits the newline, and the -u option allows you to specify a single-digit file descriptor n for the output channel. The -s option causes the output to be appended to the history file instead of an output channel. The -p option causes the output to be sent to the shell's two-way pipe channel. The -R option causes all further words to be interpreted as arguments.


Here's an example:

121 $ print -u2 hi there      ...send output to stderr. hi there 122 $ print -s echo hi there  ...append to history. 124 $ r 123                   ...recall command #123. echo hi there hi there 125 $ print -R -s hi there    ...treat "-s" as an arg. -s hi there 126 $ _ 


7.12.5.5. read

Figure 7-40 describes how the Korn shell's read command works.


[Page 288]

Figure 7-40. Description of the read shell command.

Shell Command: read -prsu [n] [name?prompt] { name }*

The Korn shell read command reads one line from standard input and then assigns successive words from the line to the specified variables. Any words that are left over are assigned to the last-named variable. The -p option causes the input line to be read from the shell's two-way pipe. The -u option causes the file descriptor n to be used for input. If the first argument contains a ?, the remainder of the argument is used as a prompt.


Here's an example:

$ read 'name?enter your name ' enter your name Graham $ echo $name Graham $ _ 


7.12.5.6. test

The Korn shell version of test accepts several new operators, listed in Figure 7-41.

Figure 7-41. Test operators unique to the Korn shell test shell command.

Operator

Meaning

-L fileName

Return true if fileName is a symbolic link.

file1 -nt file2

Return true if file1 is newer than file2.

file1 -ot file2

Return true if file1 is older than file2.

file1 -ef file2

Return true if file1 is the same file as file2.


The Korn shell also supports a more convenient syntax for test (Figure 7-42).

Figure 7-42. Two forms of test in the Korn shell.

[[ testExpression ]]


which is equivalent to:

test textExpression



I prefer the more modern form of test that uses the double brackets, as it allows me to write more readable programs. Here's an example of this newer form of test in action:

$ cat test.ksh        ...list the script. i=1 
[Page 289]
while [[ i -le 4 ]] do echo $i (( i = i + 1 )) done $ ksh test.ksh ...execute the script. 1 2 3 4 $ _


7.12.5.7. trap

The Korn shell's trap command works as shown in Figure 7-43.

Figure 7-43. Description of the trap shell command.

Shell Command: trap [ command ] [ signal ]

The Korn shell trap command instructs the shell to execute command whenever any of the numbered signals signal are received. If several signals are received, they are trapped in numeric order. If a signal value of 0 is specified, then command is executed when the shell terminates. If command is omitted, then the traps of the numbered signals are reset to their original values. If command is an empty string, then the numbered signals are ignored. If arg is -, then all of the specified signal actions are reset to their initial values. If an EXIT or 0 signal value is given to a trap inside a function, then command is executed when the function is exited. If trap is executed with no arguments, a list of all the signals and their trap settings is displayed. For more information on signals and their default actions, see Chapter 12, "Systems Programming."


In the following example, I set the EXIT trap inside a function to demonstrate local function traps:

$ cat trap.ksh                   ...list the script. f () {  echo 'enter f ()'  trap 'echo leaving f...' EXIT   # set a local trap  echo 'exit f ()' } # main program. trap 'echo exit shell' EXIT      # set a global trap. f                                # invoke the function f(). $ ksh trap.ksh                   ...execute the script. 
[Page 290]
enter f () exit f () leaving f... ...local EXIT is trapped. exit shell ...global EXIT is trapped. $ _





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

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