korn shell by marisa luvisetto

25
Shell Programming Korn Shell Marisa Luvisetto 02/05/2001

Upload: azertyui30008561

Post on 27-Nov-2014

258 views

Category:

Documents


1 download

DESCRIPTION

Learning KSH with Marisa Luvisetto

TRANSCRIPT

Page 1: Korn Shell by Marisa Luvisetto

Shell ProgrammingKorn ShellMarisa Luvisetto

02/05/2001

Page 2: Korn Shell by Marisa Luvisetto

1

Table of ContentsIntroduction............................................................................................................................................. 2

1. Korn shell variables.......................................................................................................................... 2

2. Korn shell background and foreground........................................................................................... 7

3. Korn shell arithmetic ....................................................................................................................... 8

4. Korn shell options............................................................................................................................ 9

5. Korn shell scripts ........................................................................................................................... 11

6. Korn shell exec, read and miscellaneous commands .................................................................... 20

Page 3: Korn Shell by Marisa Luvisetto

2

Introduction

Korn shell is a higher level shell. Korn shell is Bourne compatible with C shell features.The following notes are derived from The Korn Shell User and Programming Manual byAnatole Olczak published by Addison-Wesley. Korn shell will be denoted in the followingsections also either as ksh or Ksh.

A ksh command is a sequence of words separated by spaces, the first word is the commandname, the following ones are the command arguments. The command value is its exit statusthat is 200 + signal (octal) in case of abnormal termination. The exist status of a pipeline isthe value of the last command.

Ksh enables tilde substitution as described in C shell. Note that a tilde ~ followed by + isreplaced by $PWD and followed by - is replaced by $OLDPWD

In ksh, as well as in any other shell, the system needs a set of global informations in theform of name-value lists. System required names or identifiers are set at login and areknown globally via the export mechanism. Exported identifiers form the workingenvironment of the shell. Example of required identifiers are PATH that defines thecommand search path and TERM that defines the terminal type for correct processing ofcharacters such as special keys. Environment identifiers are usually divided into 2 differentgroups depending on login level setting. The basic identifiers have usually uppercasenames and are inquired by the env command. The user may assign and reassign anyidentifiers using the export or typeset -x commands. When the value of an exportedidentifier is changed, ksh exports it automatically. This feature is not supported by Bourneshell.

Ksh stores commands in a history file or buffer up to HISTSIZE commands. If the HISTFILEvariable is not set, file $HOME/.sh_history is used. The history file is manipulated by the fccommand. The editor is used according to variable FCEDIT, default /usr/bin/ed. Editing maybe handled by vi or emacs depending on user customization. For more informations on kshediting check man ksh.

1. Korn shell variables

Variables are set with the = operator as in Bourne shell. No space is allowed around the =operator. Variables may have attributes assigned by typeset with the following syntax:

Korn Shell typeset syntax

typeset -attrib(s) variable=[value] assign attribute and optional value

typeset +attrib(s) variable remove attribute

typeset list all vars and attributes

typeset -attrib list all vars with -attrib type

Page 4: Korn Shell by Marisa Luvisetto

3

typeset +attrib list only vars with +attrib type

List of typeset Supported Attributes

-f the name refers to a function

-H system to hostname file mapping

-i integer

-l lower case

-L left justify, remove leading spaces

-LZ left justify, remove leading zeroes

-r read only (cannot be removed)

-R right justify

-RZ right justify with leading zeroes

-t tag named parameter

-u upper case

-x export

Any variable can be assigned the output of a command or of a file with the syntax:

var=$(command) Korn specific

var=`command` Bourne compatible

var=$(< file) Korn specific

var=`cat file` Bourne compatible

Variables are removed by the unset builtin. To define a variable that executes a script fileusing Ksh syntax, do the following:

> ksh$ cv=$(<kls)$ echo $cvls -al$$ $cvtotal 5drwxr-xr-x 3 john users 8192 Mar 10 10:48 .drwxr-x--x 17 john users 8192 Mar 9 16:05 ..-rw-r--r-- 1 john users 299 Mar 9 11:25 a.a-rwxr-xr-x 1 john users 261 Mar 10 08:44 cread-rw-r--r-- 1 john users 37 Jun 18 1998 er

Ksh Special variables are:

Page 5: Korn Shell by Marisa Luvisetto

4

Korn Shell Special Variables

# number of positional parameters

? exit status

$ process ID

- (dash) current options

_ (underscore) the last argument of the previous command

! process ID of last background

ERRNO error no. of last failed system call

LINENO the line no. of the current script line in execution

OLDPWD previous cd directory

OPTARG last option processed by getopts

OPTIND index of last option processed by getopts

PPID parent PID

PWD current directory

RANDOM random funcion

REPLY menu item no. in response to select Ksh command

SECONDS seconds since shell invocation

CDPATH search path for cd command

COLUMNS edit window width

EDITOR editor management

ENV generate path name in tracked alias and functions

FCEDIT default editor for history processing command fc

FPATH search path for functions

IFS internal field separator

HISTFILE store command history file

HISTSIZE history buffer size

HOME home directory

LANG system locale

LC_COLLATE collating sequence

LC_CTYPE character classification

Page 6: Korn Shell by Marisa Luvisetto

5

LC_MESSAGES language for system messages

LC_MONETARY monetary format

LC_NUMERIC numeric format

LC_TIME date and time format

LINES column length

LOGNAME login name

MAIL mail notify

MAILCHECK mail notify interval

MAILPATH mail notify

NLSPATH search path for messages

PATH searc path for commands

PS1 primary promt

PS2 secondary prompt

PS3 selection prompt (default #?)

PS4 trace prompt (default +)

SHELL shell in use

TMOUT command timeout to terminate shell

VISUAL editor option

Variables are protected by braces:

$ print Current options/ERRNO: ${-}, $ERRNOCurrent options/ERRNO: ism, 10Metacharacters are printed when prefixed by \.

Korn Shell Variable Usage and Setting Rules

varlen=${#var} variable length

var=${var1:-value} var=var1 if var1 set, var=value if var1.not.set or empty

var=${var1-value} var=var1 if var1 set, var=value only if var1.not.set

var=${var1:=var2} var=$var1 if var1 set and not empty, else = $var2

var=${var1=var2} var=$var1 if var1 set even if empty, else = $var2

var=${var1:+var2} var=$var2 if var1 set and not empty, else var not set

Page 7: Korn Shell by Marisa Luvisetto

6

var=${var1:+var2} var=$var2 if var1 set even if empty, else var not set

var=${var1#var2} var=var1 with smallest part of left matched var2 deleted

var=${var1##var2} var=var1 with largest part of left matched var2 deleted

var=${var1%var2} var=var1 with smallest part of right matched var2 deleted

var=${var1%%var2} var=var1 with largest part of right matched var2 deleted

var=${var1:?} var=var1 if var1 set else error message

var=${var1:?var2} var=var1 if var1 set else var=var2 and exit

Korn shell can handle arrays as C shell but with a different syntax.

Korn Shell Array Syntax

arr[0]=val0 arr[1]=val1 ... init array in any order

set -A arr val0 val1 ... alternate init for ordered array

typeset arr[0]=val0 arr[1]=val1 ... alternate init array in any order

${arr}, $arr array element zero

${arr[n]} array element n

${arr[n+2] array element n+2

${arr[$i]} array element $i

${arr[*]}, ${arr[@]} all elements of array

${#arr[*]}, ${#arr[@]} number of array elements

${#arr[n]} length of array element n

Example of array usage:

#!/bin/ksh#-----------karray: arrays with Korn shell#echo Proc $0: arrays in Korn shellechoset -A rgb red green blue yellow magenta cyanprint rgb is a ${#rgb[*]} items color array with values:print ${rgb[*]}print 4-th item is ${rgb[1+3]} ${#rgb[4]}-bytes long##----------end script------------------The set +A statement allows partial redefinition of ordered array elements. Consider the following:

$ set -A rgb red green blue yellow magenta cyan$ print ${rgb[*]}red green blue yellow magenta cyan

Page 8: Korn Shell by Marisa Luvisetto

7

If you use -A to change only the first item of array rgb, the array is truncated. If you use +A, the firstitems are changed keeping the remaining ones:

$ set -A rgb red green blue$ print ${rgb[*]}red green blue$ set -A rgb red green blue yellow magenta cyan$ set +A rgb rosso$ print ${rgb[*]}rosso green blue yellow magenta cyan

In Korn shell quotes have the same usage as in Bourne shell.

single quotes 'hide meaning of special characters, do not perform variable substitutionwithin quoted string

double quotes "reserve embedded spaces and newlines, set vars to NULL, display singlequotes, perform variable substitution

back quotes `assign command output to vars

2. Korn shell background and foreground

Korn shell handles foreground and background jobs in the same way as C and tcsh shells.When a background job terminates a message is printed:

[2] + Done background command line....When working under Ksh (it is not enough that the script is declared ksh), background jobs areprevented from generating output by:

$ ssty tostop$ mybg &[2] 1578When some output must be printed the background job stops and signals:

$ [1] + Stopped(tty output) mybg &In this case to see mybg output the job must be restored to foreground:

$ fgmybg output lines ....If the job command is prefixed by nohup, the job output is redirected to nohup.out:

$ stty -tostop$ nohup myjob[2] Done myjob$ more nohup.outKsh jobs are accessed according to the following syntax:

Page 9: Korn Shell by Marisa Luvisetto

8

%n job number n

%str any job whose name begins with str

?str any job whose name contains str

%+ current job%- previous job%% synonimous of current job

Jobs are listed by the job command.

3. Korn shell arithmeticKorn shell arithmetic is done using the let command:$ let X=0$ let X=X+1$ print $XArithmetic operators have the same syntax as in C. The same function of the let command isachieved by ((....)) a preferred form as the brackets hide metacharacters.Variables can be declared integer by one of the commands:

$ typeset -i i=12 #-i defaults to decimal base$ integer j=44$ integer k=4+3Integer base can be specified in typeset as:

$ typeset -i2 X=5 # set binary base with -i2 or$ typeset -i X=2#101 # in the form base#valueBase definition can be used for data conversion. In the following example, a variable is set as base10 integer (X=4095), than it is printed first in hexadecimal format and than in decimal. Formatconversion is achieved using the typeset command. If the base is not 10, the base value followed by# is prefixed to the variable value, as shown in the following example:

$ typeset -i10 X; integer X=4095; echo $X4095$ typeset -i16 X; print $X16#fff$ typeset -i10 X=100; typeset -i2 Y; typeset -i16 Z; typeset -i8 O$ Y=X; Z=X; O=X$ print $X $Y $Z $O100 2#1100100 16#64 8#144

When performing arithmetic operations use the form print - of the print statement to avoidproblems with negative arguments.

Korn shell builtin $RANDOM can generate random numbers in the range 0:32767. At everycall a new random value is generated. A start value can be set by initializing the RANDOMfunction with any integer. In this case for each seed a constant random value is generated.Example:

Page 10: Korn Shell by Marisa Luvisetto

9

print random no. $RANDOMRANDOM=25print random with seed 25 is: $RANDOMtypeset -i RN=$(print $RANDOM)print RN random no. is $RNtypeset -i RN=$(RANDOM=25; print $RANDOM)print RN random no. is $RN with seed = 25Note the syntax used to assign the RANDOM value to a script variable:

typeset -i RN=$(print $RANDOM)typeset -i RN=$(RANDOM=25; print $RANDOM)The first form gives new values for each call:

$ typeset -i RN=$(print $RANDOM); $ print $RN30033$ typeset -i RN=$(print $RANDOM); print $RN14827$ typeset -i RN=$(print $RANDOM); print $RN24321while the second form produces a constant value for each seed:

$ typeset -i RN=$(RANDOM=25; print $RANDOM); print $RN27741$ typeset -i RN=$(RANDOM=25; print $RANDOM); print $RN27741$ typeset -i RN=$(RANDOM=35; print $RANDOM); print $RN32284$ typeset -i RN=$(RANDOM=35; print $RANDOM); print $RN32284

4. Korn shell options

Shell options are enabled/disabled with the set command. The option is set with set -ooption or set -option and reset with set +o option or set +option. Option setting is inquiredby:

> ksh$ set -oCurrent option settingsallexport offbgnice onemacs offerrexit offgmacs offignoreeof offinteractive onkeyword offmarkdirs offmonitor onnoexec offnoclobber offnoglob offnolog offnotify offnounset offprivileged off

Page 11: Korn Shell by Marisa Luvisetto

10

restricted offtrackall offverbose offvi offviraw offxtrace offMost useful options are:

set -a, set -o allexport export variables

set -o bgnice run background at lower priority

set -n, set -o noexec read commands without executing (debug)

set -x, set -o xtrace trace commands

For a detailed list of options check ksh man pages. Furthermore ksh can be run using oneof the following options:

-c string execute string

-i execute interactively

-r run a restricted shell

-s read commands from standard input

Ksh allows aliases as C shell but with a different syntax :

> alias cdir 'ls -al | grep "dr"' # C shell$ alias kdir='ls -al | grep "dr"' # Korn shellNote the = operator in Korn shell. Note also that no space is allowed before and after =.

In ksh the option -h of set is used to set tracked aliases. A tracked alias allows its value tobe automatically set to the full path on the corresponding command. Several tracked aliasare compiled into the shell, but can be unset or redefined.

Korn Shell Exported Aliases

autoload='typeset -u'false='let 0'functions='typeset -f'hash='alias -t'history='fc -l'integer='typeset -i'nohup='nohup'r='fc -e -'

Page 12: Korn Shell by Marisa Luvisetto

11

true=':'type='whence -v'

Korn Shell Redirection Options

<file use file as stdin

>file use file as stdout

>|file same > but ignores noclobber option

<>file use file for read/write as stdin

>>file append to file

<<[-]EOF_str read till a line containing only EOF-str is met

the dashed form <<- strips leading <tabs>

< &n associate stdin with file descriptor n

> &n associate stdout with file descriptor n

< &- close stdin

> &- close stdout

<&p input from coprocess (background) is moved to stdin

>&p output to coprocess is moved to stdout

Redirection examples:2>&1 means that file descriptor 2 is to be opened for writing as a duplicate of file descriptor1.1>file 2>&1 associates file descriptor 1 with file, then file descriptor 2 is associated withfile descriptor 1.

5. Korn shell scripts

Script arguments are the same as in Bourne shell:

$0 command name

$1...$n arguments 1 to n

$# no. of arguments

$? exit status

Page 13: Korn Shell by Marisa Luvisetto

12

Arguments can be shifted as in Bourne shell. Script execution can terminate at any placeand return an optional exit value:

exit [n]

Checks are enabled either by test or [...] (same as test) or by [[...]]. The expression isseparated from brackets by leading and trailing blanks. The double brackets form is a Kornshell enhancement.

[ "$X" = abc ] && echo string is "abc" # tcshtest "$X" = abc && echo string is "abc" # tcsh[[ $X = abc ]] && echo korn # korn

Korn Shell String Operators

-n str true if len(str) != 0

-o opt true if opt set

-z str true if len(str) = 0

str1=str2 true if equal strings

str1!=str2 true if .not.equal strings

str1=pattern true if pattern match

str1!=pattern true if pattern .not.match

str1<str2 true if str1 less than str2

str1>str2 true if str1 greater than str2

Example:

> cat kstr#!/bin/ksh#-----------kstr: string test with Korn shell#echo Proc $0: strings in Korn shellecho# set -x #uncomment to debug scriptX=nice_dogY=bad_cat[[ $X = *dog* ]] && print $X is a nice doggie[[ $Y = ??????? ]] && print $Y is 7 chars longX=123[[ $X = +([0-9]) ]] && print $X is digit[[ $Y = +([0-9)] ]] || print $Y is alpha##----------end script------------------> kstrProc kstr: strings in Korn shell

nice_dog is a nice doggiebad_cat is 7 chars long123 is digit

Page 14: Korn Shell by Marisa Luvisetto

13

bad_cat is alpha>-----------------------File testing is performed by the following operators prefixed to the file name:

> ksh -c "[[ -a kvar ]] && echo exists"exists$ ksh -c "[[ -a kls.ksh ]] || echo no such file"no such file$ [[ -a kls.ksh ]] || print no such fileno such fileThe ksh -c syntax in the above example is used when executing Ksh commands from another shelland is omitted when the test is performed with Ksh shell.Ksh test operators are mostly the same as Bourne shell ones, as described in the related table thatfollows.

Korn Shell Test Operators

-a exists

-b block special file

-c character special file

-d is directory

-e exists

-f is regular

-g setgid bit set

-G matches group ID of current process

-k sticky bit set

-L symbolic link

-n nonzero length string

-o true if named option is on

-O same UID as process

-p FIFO special file

-r readable

-s size > 0

-S socket

-t open and associate to terminal file descriptor

-u user-id bit is set

-w writable

-x executable

Page 15: Korn Shell by Marisa Luvisetto

14

-z zero length string

-ef file1 is another name for file2

-nt file1 newer than file2

-ot file1 older than file2

Test can be done also on open files using file descriptor:

$ [[ -r /dev/fd/0 ]] && print readread$ exitKorn shell supports also Fortran like test operators for integer variables:

-eq -ne -le -lt -ge -gt

Ksh control structures are:

case value in # Bourne compatible casepat1: ...... ;;

::::

patn: ...... ;;esac

Match patterns can be used in case structures. Supported patterns are:

@([a-z]) a lowercase character

@([1-9])*([0-9]) any number starting with 1

Multiple patterns are specified as (pat1 | pat2 | pat3), match criteria are:

? zero or one occurence

* zero or more occurences

@ exactly one occurence

+ one or more occurences

! all strings except pattern

Page 16: Korn Shell by Marisa Luvisetto

15

for var in word1 word2 .... wordn # Bourne compatible fordo......done

Loop over script arguments is done with the following for forms:

for var in $*for var in "$@"for varOne line for abbreviated form is:

for var in ....; do .....; doneExamples of for and if:

> cat kgrep#!/bin/ksh#-----------kgrep: search string in all files with header#-----------usage: kgrep "search string" files#echoPWD=`pwd`SRC=$1 #set SRC="search string"shift #shift 1 argumentfor FILE #loop over files pointed by the for variable FILEdo

FOUND=`grep "$SRC" $FILE`if [[ $? = 0 ]]then

print "*********************"print $PWD"/"$FILEprint ""print $FOUNDprint ""

fidone#----------end script------------------> kgrep include *.f*********************/user/james/fdev/init.f

include 'COM.INC'include 'DAT.INC'

*********************/user/james/fdev/array.f

include 'COM.INC'> grep -l ksh d* ka*init.farray.fCompare kgrep output with grep -l output that is more brief and easy to read, but prints onlyroutine names missing multiple lines matching the search substring.

In the if command the conditional clause is expressed in the double bracket form andexecution is triggered by the true (=0) or false (=1) result of the condition.Do not forget <space> separators with square brackets operators.

Page 17: Korn Shell by Marisa Luvisetto

16

if [[ .... ]]then.....fiOne line if is achieved with one of the forms:

if [[ cond ]] ; then ......; fi((cond)) && { ....; ....; }[[ cond ]] && { ....; ....; }The two forms differ for the usage of the <space> characters to delimit test fields. An example oftest on numargs with the two syntax forms is:

(($# < 1)) && { print "Usage: $0 args"; exit 1; }[[ $# < 1 ]] && { print "Usage: $0 args"; exit 1; }

The full if form is:

if ((...))then.....elif ((...))then.....else.....fiOther Korn shell loop commands are while and until that operates the reverse test.

The while and until syntax is explained below.

while ((cond)) until [[ cond ]]do do

..... ......done doneThe one line while and until forms for the loop forever condition are:

while true; do ....; doneuntil false; do ....; doneLoop conditions are exited with break n where n is the loop nesting level:

for i in a b cdo

for j in x ydo

((i == b && j == y))then

break 2else

.....fi

donedonelabel: .....#---------------end script-------------

Page 18: Korn Shell by Marisa Luvisetto

17

In the above example break 2 transfers control to label:. To interrupt only the inner loopuse break. If only a warning condition is detected, use continue instead of break. Whenimplementing loops insert a read statement in critical points to enable loop interruption andscript check in case of errors generating endless loops. An example of break and continueis given below.

#!/bin/ksh#-----------kcond: job control commands with Korn shellecho Proc $0: if/while/... in Korn shellecho(($# >= 1)) && { print "Logged users:\n`who`"; exit 0; }#nus=$(who | wc -l)if ((nus == 1))then

print "1 user logged"elif ((nus == 2))then

print "2 users logged"else

print ">2 users logged"fi#----------------B R E A K-------------------echo ""#set +x #set trace off#set -A rgb R G B Y M Cecho "while example on rgb array ${rgb[*]} - <ret> for next item - break atY"((i=0))while true

doread RETif ((i == 3))then

print "break point reached: i should be = 3 and rgb = Y"print "break values are: rgb[$i] --> ${rgb[i]}"; break

elseprint {$i}-eth RGB item is ${rgb[i]}; ((i=i+1));

fidone#----------------C O N T I N U E-------------------echo "--------------------------"echo "while example on rgb array ${rgb[*]} - <ret> for next - continue atY"((i=0))while ((i <= 5))

doread RETif ((i == 3))then

print "continue point reached: i should be = 3 and rgb = Y !!!!!"print "continue loop for remaining colors\n";print {$i}-ETH rgb ITEM IS ${rgb[i]}; ((i=i+1)); continue

elseprint {$i}-ETH rgb ITEM IS ${rgb[i]}; ((i=i+1));

fidone#---------------------------------------------------------

Page 19: Korn Shell by Marisa Luvisetto

18

Command set +x can be changed in set -x to debug script. Note the read RET statementsthat protects script from infinite loops. A <ret> is enough to procede, <ctrl>c interruptsthe script. The script produces the following output.

> kcondProc kcond: if/while/... in Korn shell

1 user logged

while example on rgb array R G B Y M C - <ret> for next item - break at Y{0}-eth RGB item is R{1}-eth RGB item is G{2}-eth RGB item is Bbreak point reached: i should be = 3 and rgb = Ybreak values are: rgb[3] --> Y-----------------------------------while example on rgb array R G B Y M C - <ret> for next - continue at Y{0}-ETH rgb ITEM IS R>A very simple way to generate menus using Ksh is given by the select command.

select menu_var in CHOICE1 ..... CHOICEndo

......doneThe select command displays the enumerated menu item list followed by the #? prompt waiting foritem value. Prompt value can be set:

$ typeset -x PS3="my pmpt>"

The user types the no. corresponding to the menu item. The typed number is stored in thebuiltin variable REPLY, while the select menu item is stored in the user variable of the selectcommand.Example:

#--------------------------------------------------------------> cat kmenuecho "Proc $0: select (menu) in Korn shell"echotypeset -x PS3="Command: "select i in PAGE PWD DIRSIN DIR ENDdo

if [[ $i = END ]]then

print "Exit option"; exit 0fiprint "Selection item $REPLY: $i"case $i in

PAGE*) page $0;;PWD*) pwd;;DIRSIN*) dirsin;;DIR*) dir;;

esacdone#----------------------------------------------------------------> kmenuProc kmenu: select (menu) in Korn shell

Page 20: Korn Shell by Marisa Luvisetto

19

1) PAGE2) PWD3) DIRSIN4) DIR5) ENDCommand: 3Selection item 3: DIRSINMar 10-rwxr-xr-x 1 mary users 380 Mar 10 12:03 kgrepTotal of 1 files, 0 blocksCommand: 5Exit option>The menu choice list can be given as script arguments with:

select menu_var; do ....; done orselect menu_var in "$@"; do ....; done

Korn Shell Print Escape Characters

\a bell

\b backspace

\c do not write newline (use for prompts)

\f formfeed

\n linefeed

\r return

\t tab

\v vertical tab

\\ backslash

\0x up to 3 digits octal no.

Print Options

- treat eveything following - as an argument

-n do not add newline

-p redirect arguments to co-process

-r ignore escape conventions

-R ignore escape; do not interpret -args as options (except -n)

-s redirect arguments to history

-un redirect arguments to file descriptor n

(default 1, if >3 must be first opened with exec)

Page 21: Korn Shell by Marisa Luvisetto

20

6. Korn shell exec, read and miscellaneous commands

The exec command is used for redirection of file descriptors 0:9. Example:

> ksh$ exec 1>std.out$ dir ~/test$ ....$ exitIn the above example, all output directed to stdout from the command exec to the commandexit is written on file std.out. To use file descriptor 5:> cat kexec# open file x.x by descriptor 5 with exec 5>x.xexec 5>x.xprint -u5 "1. redirect print output to fd 5 opened by exec"print -u5 "2. prinf on fd 5"print -u5 "3. print on fd 5 again"exec 5<&-# close file x.x with exec 5<&-echo "\n verify x.x by cat\n"The kexec script listed above creates file x.x containing the script lines 1.-2.-3..If the file descriptor is closed, any attempt to access closed file produces the following errormessage:> kexeckexec[13]: print: bad file unit numberexec may be used to execute a script but user is logged out exec is invoked when in parentshell.

The read command reads input from the terminal as single variables, piped names or fileredirected with exec as summarized in the following example.

> cat kread#!/bin/ksh#-----------kread: read data with Korn shell---------------------#echo Proc $0: read command in Korn shellechoprint "type a name> \c" # read var at prompread nameprint "typed name is: " $nameprint "\npiped read example:"print "apr may jun" | read a b c # pipe argsprint arg1 from pipe is $aprint arg2 from pipe is $bprint arg3 from pipe is $cprint "\nread/write lines with exec redirection\n"exec 0<$1 # redirect i/owhile read LINEdo

print $LINEdone##----------end script------------------

> kreadProc kread: read command in Korn shell

type a name> any

Page 22: Korn Shell by Marisa Luvisetto

21

typed name is: any

piped read example:arg1 from pipe is aprarg2 from pipe is mayarg3 from pipe is jun

read/write lines with exec redirection

line 1line 1<ctrl>C>

Korn Shell Read Options

-p read line form co-process

-r do not treat \ as continuation

-s save input in history file

-un read from file descriptor n

The prompt can be specified in the read statement:

$ read var?promptIf var is not defined, input is assigned to variable REPLY. Field separator can be assignedwith the IFS ( Internal Field Separator) variable.Example:> cat kpwd#!/bin/ksh#-----------kpwd: read example in Korn shellecho Proc $0: type pwd info with Korn shellechoread ok?"Type pwd info? (y/n)" #read with prompt[[ $ok = @([Nn])* ]] && exit 1 #test read variableecho pwd data are:echo ""IFS=: #set IFS to :exec 0</etc/passwd #redirect stdin to/etc/passwd# list users#while read -r NAME PAS UID GID COM HOME SHELLdo

print "acct= $NAME - home= $HOME - shell= $SHELL:"done#----------end script------------------> kpwd

Type pwd info? (y/n)ypwd data are:

acct= john - home= /home/john - shell= /bin/tcsh:acct= mary - home= /home/mary - shell= /bin/tcsh:acct= tester - home= /d4/check - shell= /bin/sh:>

Page 23: Korn Shell by Marisa Luvisetto

22

If you need to run a script in the current shell either use the dot [.] or the source command:$ . .profile$ source .profile$ rehashIn this way any variable, alias or function setting stay in effect. Note the rehash commandthat recreates the in-memory shell tables and grants that the system aknowledgesnew .profile definitions.

Korn shell function statement enables the creation of new commands that can takearguments. Functions are defined as follows:function f_name { commands } or f_name() { command } # BourneFunctions are exported with typeset -fx f_name.

Korn Shell set options

-flag sets flag on

+flag sets flag off

flags can be used at shell invocation

-A unset and reassign array

-a export subsequent parameters

-b notify background job completion

-C set noclobber

-e execute error trap

-f disable file name generation

-h create tracked alias

-k put all parameters in environment

-m background job message

-n check syntax error of commands without execution

-o set/type on/off options (see man)

-p disable user profile and use /etc/suid_profile

-s sort positional parameters

-t exit at command end

-u cause error if unset parameter

-v print script lines (debug)

-x print commands and arguments (debug)

- unset x and v

- - do not change flags (see man)

Page 24: Korn Shell by Marisa Luvisetto

23

Resource limit setting are nearly the same as Bourne shell with the following differences:options h, H, S are missingLimits on virtual memory and swap space are settable if the system file/usr/include/sys/resource.h defines:RLIMIT_VMEM, option -v limits Kbytes for virtual memoryRLIMT_SWAP , option -w limits Kbytes for swap area.An example of RLIMIT_VMEM definition is:

#define RLIMIT_AS 7 /* address space */#define RLIMIT_VMEM RLIMIT_AS /* V.4 alias for AS */

Korn Shell Built-in Commands

:[arg ...]1 only expand arguments

. file [arg ...]1 read file and execute commands

alias2 print/set alias, -xt for export/tracked

bg put in background

break1 exit from loop

continue1 skip loop step

cd change directory (see man)

echo write to stdout

eval1 evaluate args and execute resulting command

exec1 execute command in this shell

exit1 exit from shell

export2 export vars or type if -p option

fc edit command (see man)

fg bring in foregroud

getopts check arguments for legal options

hash rehash variable or empty list if -r option

jobs list jobs

kill kill jobs (see man)

let assign arithmetic vars

newgrp change primary group

print print command (see man)

pwd print current directory

read get input

readonly2 set var as readonly

Page 25: Korn Shell by Marisa Luvisetto

24

return1 return status

set assign vars depending on option

shift1 shift parameters (see man)

times1 print used time

trap1 execute on signal (see man)

typeset1 set shell parameters

ulimit set resource limits

umask set default protection (see man)

unalias delete named alias or all if -a

unset deassign vars

wait wait job termination

whence explain command, -pv for more specifications

inlib obsolete (see man)

rmlib obsolete (see man)

1, 2 commands 1, 2 are treated specially (see man)

In ksh commands marked 1 and 2 are treated as follows:

parameter assignements preceding command remain in effect redirection is processed after assignements errors cause script abort in command 2 words following command are expandend as parameters