Initial import of the CDE 2.1.30 sources from the Open Group.
[oweals/cde.git] / cde / programs / dtksh / ksh93.memo
1
2
3
4                                               Bell Laboratories
5
6
7
8        subject: Introduction to ksh-93        date: January 14, 1993
9                 Charge Case 311531-0101
10                 File Case 49059-6             from: David G. Korn
11                                                     MH 11267
12                                                     3C-526B x7975
13                                                     (ulysses!dgk)
14
15                                                     TM 11267-930???-93
16
17
18
19                                  ABSTRACT
20
21
22
23        ksh-93 is a major rewrite of ksh, a program that serves as a
24        command language (shell) for the  UNIX*   operating  system.
25        As  with  ksh,  ksh-93  is  essentially  compatible with the
26        System V version of the Bourne  shell[1]  ,  and  compatible
27        with previous versions of ksh.  ksh-93 is intended to comply
28        with the IEEE POSIX 1003.2 shell standard and the ISO  9945-
29        2[2] shell standard.  In addition to changes in the language
30        required  by these standards, the primary focus of ksh-93 is
31        related  to  shell   programming.    ksh-93   provides   the
32        programming  power  of  several other interpretive languages
33        such as awk[3], FIT[4], perl[5], and tcl[6].
34
35        This memo assumes that the reader is already  familiar  with
36        the  Bourne  shell.   It  introduces most of the features of
37        ksh-93 relative to the  Bourne  shell;  both  as  a  command
38        language  and  as  a  programming  language.   The  Appendix
39        contains a sample script written in ksh-93.
40
41
42
43
44
45
46
47
48
49
50        __________
51
52          * UNIX is a registered trademark of USL
53
54
55
56                       BELL LABORATORIES PROPRIETARY
57        Not for use or disclosure outside Bell Laboratories except by
58     written approval of the director of the distributing organization.
59
60
61
62
63
64
65
66
67
68
69
70                                               Bell Laboratories
71
72
73
74        subject: Introduction to ksh-93        date: January 14, 1993
75                 Charge Case 311531-0101
76                 File Case 49059-6             from: David G. Korn
77                                                     MH 11267
78                                                     3C-526B x7975
79                                                     (ulysses!dgk)
80
81                                                     TM 11267-930???-93
82
83
84
85                            MEMORANDUM_FOR_FILE
86
87
88
89        1.  INTRODUCTION
90
91        The term "shell" is used to describe a program that provides
92        a command language interface.   Because  the  UNIX*   system
93        shell is a user level program, and not part of the operating
94        system itself, anyone can write a new  shell  or  modify  an
95        existing  one.   This has caused an evolutionary progress in
96        the design and implementation of  shells,  with  the  better
97        ones  surviving.   The  most  widely  available  UNIX system
98        shells are the Bourne shell[7], written by Steve  Bourne  at
99        AT&T Bell Laboratories, the C shell[8], written by Bill  Joy
100        at the University of California, Berkeley, and the KornShell
101        language  [9],  written  by  David   Korn   at   AT&T   Bell
102        Laboratories.   The  Bourne shell is available on almost all
103        versions of the UNIX system.  The C Shell is available  with
104        all Berkeley Software Distribution, BSD, UNIX systems and on
105        many other systems.  The KornShell, is available on System V
106        Release  4  systems.  In  addition,  it is available on many
107        other systems.  The source for  the  KornShell  language  is
108        available  from  the  AT&T Toolchest, an electronic software
109        distribution system.  It runs on all known versions  of  the
110        UNIX system and on many UNIX system look-alikes.
111
112        There have been several articles comparing the  UNIX  system
113        shells.   Jason  Levitt[10]  highlights  some  of  the   new
114
115
116        __________
117
118          * UNIX is a registered trademark of USL
119
120
121
122                       BELL LABORATORIES PROPRIETARY
123        Not for use or disclosure outside Bell Laboratories except by
124     written approval of the director of the distributing organization.
125
126
127
128
129
130
131
132
133
134
135
136                                   - 2 -
137
138
139
140        features  introduced  by  the  KornShell   language.    Rich
141        Bilancia[11] explains some of the advantages  of  using  the
142        KornShell language.  John Sebes[12] provides a more detailed
143        comparison  of  the three shells, both as a command language
144        and as a programming language.
145
146        The KornShell language is a superset of  the  Bourne  shell.
147        The  KornShell  language  has  many  of  the popular C shell
148        features, plus additional features of its own.  Its  initial
149        popularity  stems  primarily  from  its  improvements  as  a
150        command language.  The primary interactive  benefit  of  the
151        KornShell  command  language is a visual command line editor
152        that allows you to make corrections to your current  command
153        line  or  to earlier command lines, without having to retype
154        them.
155
156        However, in  the  long  run,  the  power  of  the  KornShell
157        language  as a high-level programming language, as described
158        by Dolotta and  Mashey[13],  may  prove  to  be  of  greater
159        significance.   ksh-93  provides  the  programming  power of
160        several other interpretive languages such as awk, FIT, perl,
161        and  tcl.  An application that was originally written in the
162        C  programming  language  was  rewritten  in  the  KornShell
163        language.   More  than  20,000 lines of C code were replaced
164        with KornShell scripts totaling fewer than  700  lines.   In
165        most  instances  there  was  no  perceptible  difference  in
166        performance between the two versions of the code.
167
168        The KornShell language  has  been  embedded  into  windowing
169        systems  allowing  graphical user interfaces to be developed
170        in shell rather than having to build applications that  need
171        to be compiled.  The wksh program[14], provides a method  of
172        developing OpenLook or Motif applications as ksh scripts.
173
174        This memo is an introduction  to  ksh-93  the  program  that
175        implements  an  enhanced  version of the KornShell language.
176        It is referred to as ksh in the rest of this memo.  The memo
177        describes  the  KornShell  language based on the features of
178        the 02/25/93 release of ksh.  This memo is not  a  tutorial,
179        only  an  introduction.  The second edition of reference [9]
180        gives a more complete treatment of the KornShell language.
181
182        A concerted effort has been made to achieve  both  System  V
183        Bourne  shell  compatibility and IEEE POSIX compatibility so
184        that scripts written for either  of  these  shells  can  run
185        without modification with ksh.  In addition, ksh-93 attempts
186
187
188                       BELL LABORATORIES PROPRIETARY
189        Not for use or disclosure outside Bell Laboratories except by
190     written approval of the director of the distributing organization.
191
192
193
194
195
196
197
198
199
200
201
202                                   - 3 -
203
204
205
206        to be compatible with older versions of ksh.  When conflicts
207        between  these  versions  of  the  shell, ksh-93 selects the
208        behavior  dictated  by  the  IEEE   POSIX   standard.    The
209        description of features in this memo assumes that the reader
210        is already familiar with the Bourne shell.
211
212
213        2.  COMMAND LANGUAGE
214
215        There is no separate command language.  All features of  the
216        language,  except  job  control,  can  be used both within a
217        script and interactively from a terminal.  However, features
218        that  are  more  likely  to  be  used while running commands
219        interactively from a terminal are presented here.
220
221        2.1  Setting Options
222
223        By convention, UNIX  commands  consist  of  a  command  name
224        followed by options and other arguments.  Options are either
225        of the form -letter, or -letter value.  In the former  case,
226        several  options  may  be  grouped  after  a  single -.  The
227        argument -- signifies an end to the option list and is  only
228        required when the first non-option argument begins with a -.
229        Most commands print  an  error  message  which  shows  which
230        options   are  permitted  when  given  incorrect  arguments.
231        Ordinarily, ksh executes a command by using the command name
232        to  locate  a program to run and by running the program as a
233        separate process.  Some commands, referred to as  built-ins,
234        are  carried  out by ksh itself, without creating a separate
235        process.  The reasons that some commands  are  built-in  are
236        presented  later.   In  nearly  all  cases  the  distinction
237        between a command that is built-in and one that  is  not  is
238        invisible  to  the  user.  However, nearly all commands that
239        are built-in follow command line conventions.  In  addition,
240        the  option  sequence -? causes the command to print a usage
241        message which lists the valid options.
242
243        ksh has several options that can  be  set  by  the  user  as
244        command  line  arguments  and as option arguments to the set
245        command.  Most options can  be  set  with  a  single  letter
246        option  or  as a name that follows the -o option. Use set -o
247        to display the  current  option  settings.   Some  of  these
248        options,  such  as  interactive and monitor (See Job Control
249        below) are enabled automatically by ksh when  the  shell  is
250        connected  to  a  terminal  device.   Other options, such as
251        noclobber and ignoreeof are normally  placed  in  a  startup
252
253
254                       BELL LABORATORIES PROPRIETARY
255        Not for use or disclosure outside Bell Laboratories except by
256     written approval of the director of the distributing organization.
257
258
259
260
261
262
263
264
265
266
267
268                                   - 4 -
269
270
271
272        file.   The  noclobber  option  causes ksh to print an error
273        message when you use > to redirect to a  file  that  already
274        exists,  If  you  want to redirect to an existing file, then
275        you have to use >| to override the  noclobber  option.   The
276        ignoreeof   option   is  used  to  prevent  the  end-of-file
277        character, normally ^D(Control-d), from  exiting  the  shell
278        and  possibly  logging  you  out.  You must type exit to log
279        out.  Most of the options are  described  in  this  memo  as
280        appropriate.
281
282        2.2  Command Aliases
283
284        Command aliases provide a mechanism of associating a command
285        name  and  options with a shorter name.  Aliases are defined
286        with the alias built-in.   The  form  of  an  alias  command
287        definition is:
288                              alias name=value
289        As with other shell assignments, no space is allowed  before
290        or  after  the =.  The characters of an alias name cannot be
291        characters that are special to the  shell.  The  replacement
292        string, value, can contain any valid shell script, including
293        meta-characters such as  pipe  symbols  and  i/o-redirection
294        provided  that  they are quoted.  Unlike csh, aliases in ksh
295        cannot take  arguments.   The  equivalent  functionality  of
296        aliases  with  arguments  can  only  be  achieved with shell
297        fucntions described later.
298
299        As a command is being read,  the  command  name  is  checked
300        against  a list of alias names.  If it is found, the name is
301        replaced by the alias value associated with  the  alias  and
302        then  rescanned.   When  rescanning  the value for an alias,
303        alias substitutions are performed except for an  alias  that
304        is  currently being processed.  This prevents infinite loops
305        in alias  substitutions.   For  example  with  the  aliases,
306        alias l=ls 'ls=ls -C',  the command name l becomes ls, which
307        becomes ls -C.  Ordinarily, only the command  name  word  is
308        processed  for alias substitution.  However, if the value of
309        an alias ends in a space, then the word following the  alias
310        is  also  checked  for  alias  substitution.   This makes it
311        possible to define an alias whose first argument is the name
312        of  a  command and have alias substitution performed on this
313        argument, for example nohup='nohup '.
314
315        Aliases can be used to redefine built-in  commands  so  that
316        the alias,
317                             alias test=./test
318
319
320                       BELL LABORATORIES PROPRIETARY
321        Not for use or disclosure outside Bell Laboratories except by
322     written approval of the director of the distributing organization.
323
324
325
326
327
328
329
330
331
332
333
334                                   - 5 -
335
336
337
338        can be used  to  look  for  test  in  your  current  working
339        directory  rather  than  using  the  built-in  test command.
340        Reserved words such as for and while cannot  be  changed  by
341        aliasing.  The command alias, without arguments, generates a
342        list of aliases and corresponding alias values.  The unalias
343        command removes the name and text of an alias.
344
345        Aliases are used to save typing and to  improve  readability
346        of  scripts.   Several  aliases  are predefined by ksh.  For
347        example, the predefined alias
348                         alias integer='typeset -i'
349        allows the integer variables i and  j  to  be  declared  and
350        initialized with the command
351                              integer i=0 j=1
352
353        While  aliases  can  be  defined  in  scripts,  it  is   not
354        recommended.   The  location  of  an  alias  command  can be
355        important since aliases are only processed when a command is
356        read.   A  .   procedure (the shell equivalent to an include
357        file) is read all at once (unlike start up files  which  are
358        read  a command at a time) so that any aliases defined there
359        will not effect any commands within this script.  Predefined
360        aliases do not have this problem.
361
362        2.3  Command Re-entry
363
364        When run interactively, ksh saves the commands you type at a
365        terminal  in a file.  If the variable HISTFILE is set to the
366        name of a file to which the user has write access, then  the
367        commands  are  stored  in  this history file.  Otherwise the
368        file $HOME/.sh_history is checked for write  access  and  if
369        this  fails  an  unnamed  file  is  used to hold the history
370        lines.   Commands  are  always  appended   to   this   file.
371        Instances  of  ksh  that  run  concurrently and use the same
372        history file name, share access to the history file so  that
373        a command entered in one shell will be available for editing
374        in another shell.   The  file  may  be  truncated  when  ksh
375        determines  that  no  other shell is using the history file.
376        The number of commands accessible to the user is  determined
377        by  the value of the HISTSIZE variable at the time the shell
378        is invoked.  The default value is  128.   Each  command  may
379        consist  of  one  or  more lines since a compound command is
380        considered one command.   If  the  character  !   is  placed
381        within  the  primary prompt string, PS1, then it is replaced
382        by the command number each time the prompt is given.
383
384
385
386                       BELL LABORATORIES PROPRIETARY
387        Not for use or disclosure outside Bell Laboratories except by
388     written approval of the director of the distributing organization.
389
390
391
392
393
394
395
396
397
398
399
400                                   - 6 -
401
402
403
404        A built-in command named hist is used to  list  and/or  edit
405        any  of  these  saved  commands.   The  option -l is used to
406        specify listing  of  previous  commands.   The  command  can
407        always  be  specified  with a range of one or more commands.
408        The range can be specified by  giving  the  command  number,
409        relative  or  absolute,  or by giving the first character or
410        characters of the command.  When  given  without  specifying
411        the range, the last 16 commands are listed, each preceded by
412        the command number.
413
414        If the listing option is not selected,  then  the  range  of
415        commands  specified,  or  the  last  command  if no range is
416        given, is passed to  an  editor  program  before  being  re-
417        executed  by  ksh.   The  editor to be used may be specified
418        with the option -e and following it with  the  editor  name.
419        If  this  option  is  not  specified, the value of the shell
420        variable HISTEDIT  is  used  as  the  name  of  the  editor,
421        providing  that  this  variable has non-null value.  If this
422        variable is not set, or is null, and the -e option  has  not
423        been  selected, then /bin/ed is used.  When editing has been
424        complete, the edited text automatically  becomes  the  input
425        for ksh.  As this text is read by ksh, it is echoed onto the
426        terminal.
427
428        The -s option causes the editing to  be  bypassed  and  just
429        re-executes the command.  In this case only a single command
430        can be specified as the range and an  optional  argument  of
431        the form old=new may be added which requests a simple string
432        substitution prior to evaluation.  A convenient alias,
433                             alias r='hist -s'
434        has been pre-defined so that the single key-stroke r can  be
435        used  to  re-execute the previous command and the key-stroke
436        sequence, r abc=def c can be used  to  re-execute  the  last
437        command  that  starts  with  the  letter  c  with  the first
438        occurrence of the string abc replaced with the  string  def.
439        Typing   r c > file  re-executes  the  most  recent  command
440        starting with the letter c, with standard output  redirected
441        to file.
442
443        2.4  In-line editing
444
445        Lines typed from a terminal  frequently  need  changes  made
446        before entering them.  With the Bourne shell the only method
447        to fix up commands is by backspacing or  killing  the  whole
448        line.   ksh offers options that allow the user to edit parts
449        of the current command line before submitting  the  command.
450
451
452                       BELL LABORATORIES PROPRIETARY
453        Not for use or disclosure outside Bell Laboratories except by
454     written approval of the director of the distributing organization.
455
456
457
458
459
460
461
462
463
464
465
466                                   - 7 -
467
468
469
470        The in-line edit options make the command line into a single
471        line screen edit window.  When the command  is  longer  than
472        the  width of the terminal, only a portion of the command is
473        visible.  Moving within the line  automatically  makes  that
474        portion  visible.   Editing  can be performed on this window
475        until the return key is pressed.   The  editing  modes  have
476        editing  directives  that  access  the history file in which
477        previous commands are saved.  A user can  copy  any  of  the
478        most  recent HISTSIZE commands from this file into the input
479        edit window.  You can locate commands  by  searching  or  by
480        position.
481
482        The in-line editing  options  do  not  use  the  termcap  or
483        terminfo  databases.   They work on most standard terminals.
484        They only require that the  backspace  character  moves  the
485        cursor  left  and the space character overwrites the current
486        character on the screen and moves the cursor to  the  right.
487        Very  few  terminals  or terminal emulators do not have this
488        behavior.
489
490        There is a choice of editor options.  The emacs,  gmacs,  or
491        vi option is selected by turning on the corresponding option
492        of the set command.  If the value of the  EDITOR  or  VISUAL
493        variables  ends with any of these suffixes the corresponding
494        option is turned on.   A  large  subset  of  each  of  these
495        editors'   features   are   available   within   the  shell.
496        Additional functions, such as  file  name  completion,  have
497        also been added.
498
499        In the emacs or gmacs mode the user positions the cursor  to
500        the  point  needing  correction  and  inserts,  deletes,  or
501        replaces characters as needed.  The only difference  between
502        these two modes is the meaning of the directive ^T.  Control
503        keys and escape sequences are used  for  cursor  positioning
504        and  control functions.  The available editing functions are
505        listed in the manual page.
506
507        The vi editing mode starts in insert mode and enters control
508        mode when the user types ESC ( 033 ).  The return key, which
509        submits the current command for processing, can  be  entered
510        from  either  mode.  The cursor can be anywhere on the line.
511        A  subset  of  commonly  used  vi  editing  directives   are
512        available.  The k and j directives that normally move up and
513        down by one line, move  up  and  down  one  command  in  the
514        history  file,  copying  the  command  into  the  input edit
515        window.  For reasons of efficiency, the terminal is kept  in
516
517
518                       BELL LABORATORIES PROPRIETARY
519        Not for use or disclosure outside Bell Laboratories except by
520     written approval of the director of the distributing organization.
521
522
523
524
525
526
527
528
529
530
531
532                                   - 8 -
533
534
535
536        canonical  mode  until  an ESC is typed.  On some terminals,
537        and on earlier versions of the UNIX operating  system,  this
538        doesn't work correctly.  The viraw option, which always uses
539        raw or cbreak mode, must be used in this case.
540
541        Most of the code for the editing options does  not  rely  on
542        the ksh code and can be used in a stand-alone mode with most
543        any command to add in-line edit  capability.   However,  all
544        versions  of the in-line editors have some features that use
545        some shell specific code.  For example, with all edit modes,
546        the ESC-= directive applied to command words (the first word
547        on the line, or the first word after a ;, |, (, or &)  lists
548        all  aliases,  functions, or commands that match the portion
549        of the given current word.  When  applied  to  other  words,
550        this  directive  prints  the  names  of files that match the
551        current word.  The ESC-* directive adds the expanded list of
552        matching  files  to the command line.  A trailing * is added
553        to the word if it doesn't contain any file pattern  matching
554        characters  before  the expansion.  In emacs and gmacs mode,
555        ESC-ESC indicates command completion when applied to command
556        names,  otherwise  it  indicates  pathname completion.  With
557        command or pathname completion, the list  generated  by  the
558        ESC-=  directive  is  examined  to  find  the longest common
559        prefix.  With command completion, only the last component of
560        the  pathname is used to compute the longest command prefix.
561        If the longest common prefix is a complete match, then  word
562        is replaced by the pathname, and a / is appended if pathname
563        is a directory, otherwise a space is added.  In vi  mode,  \
564        from control mode gives the same behavior.
565
566        2.5  Key Binding
567
568        It is possible to intercept keys as  they  are  entered  and
569        apply  new  meanings  or  bindings.   A  trap named KEYBD is
570        evaluated each time the user enters a key from the keyboard,
571        except  while  entering a search string or an argument to an
572        edit directive such as r in vi-mode.  The action  associated
573        with  this  trap  can change the value of the entered key to
574        cause the key to perform a different operation.
575
576        When the KEYBD trap  is  entered,  the  .sh.edtext  variable
577        contains  the  contents  of  the  current input line and the
578        .sh.edcol variable gives the current cursor position  within
579        this   line.   The  .sh.edmode  variable  contains  the  ESC
580        character when the trap is entered from insert  mode  of  vi
581        mode.   Otherwise,  this  value  is  null.   The  .sh.edchar
582
583
584                       BELL LABORATORIES PROPRIETARY
585        Not for use or disclosure outside Bell Laboratories except by
586     written approval of the director of the distributing organization.
587
588
589
590
591
592
593
594
595
596
597
598                                   - 9 -
599
600
601
602        variable contains the  character  or  escape  sequence  that
603        caused  the trap.  The value of .sh.edchar at the end of the
604        trap will be used as the input sequence.
605
606        Using the associative array facility of ksh described later,
607        and  the  function  facility  of  ksh, it is easy to write a
608        single trap so that keys  can  be  bound  dynamically.   For
609        example,
610
611             typeset -A Keybind
612             trap 'eval "${Keybind[${.sh.edchar}]}"' KEYBD
613             function keybind # key seq
614             {
615                    Keybind[$1]=".sh.edchar=${.sh.edmode}$2"
616             }
617
618
619        2.6  Job Control
620
621        The job control mechanism is almost identical to the version
622        found  in csh of the Berkeley UNIX operating system, version
623        4.1 and later.  The job control feature allows the  user  to
624        stop  and restart programs, and to move programs to and from
625        the foreground and the background.  It  will  only  work  on
626        systems  that  provide support for these features.  However,
627        even systems without job control have a monitor option which
628        when  enabled,  will  report the progress of background jobs
629        and enable the user to kill jobs by job number or job name.
630
631        An interactive shell associates a  job  with  each  pipeline
632        typed  in from the terminal and assigns them a small integer
633        number  called  the  job  number.   If  the   job   is   run
634        asynchronously,  the  job number is printed at the terminal.
635        At any given time, only one job  owns  the  terminal,  i.e.,
636        keyboard  signals are only sent to the processes in one job.
637        When ksh creates a foreground job, it gives it ownership  of
638        the  terminal.  If you are running a job and wish to stop it
639        you hit the key ^Z (control-Z) which sends a STOP signal  to
640        all  processes  in  the  current  job.   The  shell receives
641        notification that the processes have stopped and takes  back
642        control of the terminal.
643
644        There are commands to continue programs  in  the  foreground
645        and  background.   There  are several ways to refer to jobs.
646        The character % introduces a job name.   You  can  refer  to
647        jobs by name or number as described in the manual page.  The
648
649
650                       BELL LABORATORIES PROPRIETARY
651        Not for use or disclosure outside Bell Laboratories except by
652     written approval of the director of the distributing organization.
653
654
655
656
657
658
659
660
661
662
663
664                                   - 10 -
665
666
667
668        built-in command bg allows you to  continue  a  job  in  the
669        background,  while  the  built-in  command  fg allows you to
670        continue a job in the foreground even though  you  may  have
671        started it in the background.
672
673        A job being run in the background will stop if it  tries  to
674        read  from  the  terminal.   It  is  also  possible  to stop
675        background jobs that try to write on the terminal by setting
676        the terminal options appropriately.
677
678        There is a built-in command jobs that lists  the  status  of
679        all running and stopped jobs.  In addition, you are informed
680        of  the  change  of  state  (running  or  stopped)  of   any
681        background  jobs just before each prompt.  If you want to be
682        notified about background job completions as  soon  as  they
683        occur  without  waiting  for  a  prompt, then use the notify
684        option.  When you try to  exit  the  shell  while  jobs  are
685        stopped or running, you will receive a message from ksh.  If
686        you ignore this message and try to exit again,  all  stopped
687        processes  will  be  terminated.   In  addition,  for  login
688        shells, the HUP signal will be sent to all  background  jobs
689        unless the job has been disowned with the disown command.
690
691        A built-in version of kill makes  it  possible  to  use  job
692        numbers  as targets for signals.  Signals can be selected by
693        number or name.  The name of the signal is the name found in
694        the  include  file /usr/include/sys/signal.h with the prefix
695        SIG removed.  The -l option of kill provides a means to  map
696        individual  signal  names  to  and  from  signal number.  In
697        addition, if no signal name  or  number  is  given,  kill -l
698        generates a list of valid signal names.
699
700        2.7  Changing Directories
701
702        By default, ksh maintains a logical view of the file  system
703        hierarchy  which  makes  symbolic  links  transparent.   For
704        systems that have symbolic links, this means that if /bin is
705        a  symbolic  link  to  /usr/bin  and you change directory to
706        /bin, pwd will indicate that you are in /bin, not  /usr/bin.
707        pwd -P  generates  the  physical  pathname  of  the  present
708        working directory by resolving all the symbolic  links.   By
709        default, the cd command will take you where you expect to go
710        even if you cross symbolic links.  A subsequent cd .. in the
711        example  above  will  place  you in /, not /usr.  On systems
712        with  symbolic  links,  cd -P  causes  ..   to  be   treated
713        physically.
714
715
716                       BELL LABORATORIES PROPRIETARY
717        Not for use or disclosure outside Bell Laboratories except by
718     written approval of the director of the distributing organization.
719
720
721
722
723
724
725
726
727
728
729
730                                   - 11 -
731
732
733
734        ksh remembers your last directory in  the  variable  OLDPWD.
735        The  cd  built-in  can be given with argument - to return to
736        the previous directory and prints the name of the directory.
737        Note  that  cd -  done  twice  returns  you  to the starting
738        directory, not the second previous directory.   A  directory
739        stack  manager  has  been written as shell functions to push
740        and pop directories from the stack.
741
742        2.8  Prompts
743
744        When ksh reads commands from a terminal, it issues a  prompt
745        whenever it is ready to accept more input and then waits for
746        the user to respond.  The TMOUT variable can be  set  to  be
747        the  number  of  seconds  that the shell will wait for input
748        before terminating.  A 60 second warning message is  printed
749        before terminating.
750
751        The shell uses two prompts.  The primary prompt, defined  by
752        the  value  of  the  PS1 variable, is issued at the start of
753        each command.  The secondary prompt defined by the value  of
754        the  PS2  variable,  is  issued when more input is needed to
755        complete a command.
756
757        ksh  allows  that  user  to  specify  a  list  of  files  or
758        directories  to  check  before  issuing the PS1 prompt.  The
759        variable MAILPATH is a colon ( : ) separated  list  of  file
760        names  to  be  checked for changes periodically. The user is
761        notified before the next prompt.  Each of the names in  this
762        list can be followed by a ?  and a prompt to be given when a
763        change has been detected in the file.  The  prompt  will  be
764        evaluated  for  parameter  substitution.   The  parameter $_
765        within a mail message will evaluate to the name of the  file
766        that  has  changed.   The  parameter  MAILCHECK  is  used to
767        specify the minimal interval in seconds before new  mail  is
768        checked for.
769
770        In addition to replacing each !   in  the  prompt  with  the
771        command  version,  ksh expands the value of the PS1 variable
772        for  parameters  expansions,  arithmetic   expansions,   and
773        command  substitutions  as  described  below to generate the
774        prompt.  The expansion characters that  are  to  be  applied
775        when  the  prompt  is  issued  must be quoted to prevent the
776        expansions from occurring when assigning the value  to  PS1.
777        For example, PS1="$PWD" causes PS1 to be set to the value of
778        PWD at the time of the assignment whereas PS1='$PWD'  causes
779        PWD to be expanded at the time the prompt is issued.
780
781
782                       BELL LABORATORIES PROPRIETARY
783        Not for use or disclosure outside Bell Laboratories except by
784     written approval of the director of the distributing organization.
785
786
787
788
789
790
791
792
793
794
795
796                                   - 12 -
797
798
799
800        Command substitution  may  require  a  separate  process  to
801        execute  and  cause  the prompt display to be somewhat slow,
802        especially when the return key is pressed several times in a
803        row.   Therefore,  its  use within PS1 is discouraged.  Some
804        variables are maintained by ksh so that their values can  be
805        used  with PS1.  The PWD variable stores the pathname of the
806        current working directory.  The value of SECONDS variable is
807        the  value  of  the  most recent assignment plus the elapsed
808        time.  By default, the time is  measured  in  milli-seconds,
809        but  since  SECONDS is a floating point variable, the number
810        of places after the decimal point in the expanded value  can
811        be specified with typeset -Fplaces SECONDS.  In a roundabout
812        way, this variable can be used to generate a time stamp into
813        the  PS1  prompt  without creating a process at each prompt.
814        The following code explains how you can do this on System V.
815        On  BSD,  you need another command to initialize the SECONDS
816        variable.
817
818
819             # . this script and use $TIME as part of your PS1 string to
820             # get the time of day in your prompt
821             typeset -RZ2  _x1 _x2 _x3
822             (( SECONDS=$(date  '+3600*%H+60*%M+%S') ))
823             _s='_x1=(SECONDS/3600)%24,_x2=(SECONDS/60)%60,_x3=SECONDS%60,0'
824             TIME='"${_d[_s]}$_x1:$_x2:$_x3"'
825             # PS1=${TIME}whatever
826
827
828
829        2.9  Tilde substitution
830
831        The character ~ at the  beginning  of  a  word  has  special
832        meaning  to  ksh.   If  the characters after the ~ up to a /
833        match a user login name in the password database, then the ~
834        and  the  name  are replaced by that user's login directory.
835        If no match is found, the original word is unchanged.   A  ~
836        by  itself,  or in front of a /, is replaced by the value of
837        the HOME parameter.  A ~ followed by a + or - is replaced by
838        the value of $PWD and $OLDPWD respectively.
839
840        2.10  Output formats
841
842        The output of  built-in  commands  and  traces  have  values
843        quoted  so  that  they  can  be re-input to the shell.  This
844        makes it easy to use cut and paste shell output  on  systems
845        which  use  a pointing device such as a mouse.  In addition,
846
847
848                       BELL LABORATORIES PROPRIETARY
849        Not for use or disclosure outside Bell Laboratories except by
850     written approval of the director of the distributing organization.
851
852
853
854
855
856
857
858
859
860
861
862                                   - 13 -
863
864
865
866        output can be saved in a file for reuse.
867
868        2.11  The ENV file
869
870        When an  interactive  ksh  starts,  it  evaluates  the  $ENV
871        variable  to  arrive  at  a file name.  If this value is not
872        null, ksh attempts to read and process commands in a file by
873        this  name.   Earlier  versions of ksh read the ENV file for
874        all invocations of the shell  primarily  to  allow  function
875        definitions  to be available for all shell invocations.  The
876        function search path, FPATH, described later, eliminated the
877        primary  need for this capability and it was removed because
878        the high performance cost was no longer deemed acceptable.
879
880
881        3.  PROGRAMMING LANGUAGE
882
883        The KornShell vastly extends the set  of  applications  that
884        can  be implemented efficiently at the shell level.  It does
885        this by providing simple yet powerful mechanisms to  perform
886        arithmetic,  pattern  matching,  substring  generation,  and
887        arrays.  Users can write applications as separate  functions
888        that  can  be  defined  in  the same file or in a library of
889        functions stored in a directory and loaded on demand.
890
891        3.1  String Processing
892
893        The shell is primarily a  string  processing  language.   By
894        default,  variables hold variable length strings.  There are
895        no limits to the length of strings.  Storage  management  is
896        handled  by  the  shell automatically.  Declarations are not
897        required.  With most programming languages, string constants
898        are  designated  by enclosing characters in single quotes or
899        double quotes.  Since most of the words in the language  are
900        strings,  the  shell  requires  quotes  only  when  a string
901        contains characters that are normally processed specially by
902        the  shell, but their literal meaning is intended.  However,
903        since the shell is a string processing  language,  and  some
904        characters   can   occur   as   literals   and  as  language
905        metacharacters,  quoting  is  an  important  part   of   the
906        language.
907
908        There are four quoting mechanisms in ksh.  The  simplest  is
909        to  enclose  a  sequence of characters inside single quotes.
910        All characters between a pair of single  quotes  have  their
911        literal meaning; the single quote itself cannot appear.  A $
912
913
914                       BELL LABORATORIES PROPRIETARY
915        Not for use or disclosure outside Bell Laboratories except by
916     written approval of the director of the distributing organization.
917
918
919
920
921
922
923
924
925
926
927
928                                   - 14 -
929
930
931
932        immediately preceding a single quoted string causes all  the
933        characters until the matching single quote to be interpreted
934        as  an  ANSI-C  language  string.   Thus,  '\n'   represents
935        characters  \  and n, whereas, $'\n' represents the new-line
936        character.  Double quoted strings remove the special meaning
937        of  all  characters  except  $,  and  `,  so  that parameter
938        expansion  and  command  substitution  (defined  below)  are
939        performed.   The  final mechanism for quoting a character is
940        by preceding it with the escape character \.  This mechanism
941        works outside of quoted strings and for the characters $, `,
942        ", and \ in double quoted strings.
943
944        Variables  are  designated  by  one  or  more   strings   of
945        alphanumeric   characters   beginning   with  an  alphabetic
946        character separated by a ..  Upper and lowercase  characters
947        are  distinct,  so  that  the  variable A and a are names of
948        different variables.  There is no limit to the length of the
949        name  of  a variable.  You do not have to declare variables.
950        You can assign a value to a variable by writing the name  of
951        the  variable,  followed  by  an  equal  sign, followed by a
952        character string that represents its  value.   To  create  a
953        variable  whose  name  contains a ., the variable whose name
954        consists of the characters before the last .   must  already
955        exist.   You reference a variable by putting the name inside
956        curly braces and preceding the braces with  a  dollar  sign.
957        The braces may be omitted when the name is alphanumeric.  If
958        x and y are two  shell  variables,  then  to  define  a  new
959        variable,  z, whose value is the concatenation of the values
960        of x and y, you just say z=$x$y.  It is that easy.
961
962        The $ can be thought of as meaning "value of." You can  also
963        capture   the  output  of  any  command  with  the  notation
964        $(command).  This is referred to  as  command  substitution.
965        For  example,  x=$(date)  assigns  the  output from the date
966        command to the variable  x.   Command  substitution  in  the
967        Bourne  shell  is  denoted  by enclosing the command between
968        backquotes,  (``).   This   notation   suffers   from   some
969        complicated  quoting  rules.   Thus, it is hard to write sed
970        patterns  which  contains  back   slashes   within   command
971        substitution.   Putting  the  pattern in single quotes is of
972        little  help.   ksh  accepts  the   Bourne   shell   command
973        substitution   syntax   for   backward  compatibility.   The
974        $(command) notation allows the  command  itself  to  contain
975        quoted strings even if the substitution occurs within double
976        quotes. Nesting is legal.
977
978
979
980                       BELL LABORATORIES PROPRIETARY
981        Not for use or disclosure outside Bell Laboratories except by
982     written approval of the director of the distributing organization.
983
984
985
986
987
988
989
990
991
992
993
994                                   - 15 -
995
996
997
998        The special command substitution of the form $(cat file) can
999        be  replaced  by  $(< file), which is faster because the cat
1000        command doesn't have to run.
1001
1002        3.2  Shell Parameters and Variables
1003
1004        There are three types of parameters  used  by  ksh,  special
1005        parameters,  positional  parameters,  and  named  parameters
1006        which are called variables.  ksh defines  the  same  special
1007        characters,  0, *, @, #, ?, $, !, and -, as they are defined
1008        in the Bourne shell.
1009
1010        Positional parameters are set when the shell is invoked,  as
1011        arguments  to  the  set  built-in, and by calls to functions
1012        (see below) and .  procedures.  They are named by  a  number
1013        starting at 1.
1014
1015        The third type of parameter is  a  variable.   As  mentioned
1016        earlier,  ksh  uses  variables whose names consist of one or
1017        more alpha-numeric strings separated by a ..   There  is  no
1018        need to specify the type of a variable in the shell because,
1019        by default, variables store strings of arbitrary length  and
1020        values  will automatically be converted to numbers when used
1021        in an arithmetic context.  However, ksh variables  can  have
1022        one   or   more   attributes   that   control  the  internal
1023        representation of the variable,  the  way  the  variable  is
1024        printed,  and  its access or scope.  In addition, ksh allows
1025        variables to represent arrays of values  and  references  to
1026        other  variables.   The  typeset  built-in  command  of  ksh
1027        assigns attributes to variables.   Two  of  the  attributes,
1028        readonly  and  export,  are  available  in the Bourne shell.
1029        Most of the remaining attributes are  discussed  here.   The
1030        complete  list  of  attributes  appears  in the manual.  The
1031        unset built-in of  ksh  removes  values  and  attributes  of
1032        variables.   When  a  variable  is  exported, certain of its
1033        attributes are also exported.
1034
1035        Whenever a value is assigned to a  variable,  the  value  is
1036        transformed  according  to  the  attributes of the variable.
1037        Changing the attribute of a variable can change  its  value.
1038        The  attributes  -L  and  -R  are  for  left and right field
1039        justification respectively.  They are  useful  for  aligning
1040        columns  in a report.  For each of these attributes, a width
1041        can be defined explicitly or else it is  defined  the  first
1042        time an assignment is made to the variable.  Each assignment
1043        causes justification of the field, truncating if  necessary.
1044
1045
1046                       BELL LABORATORIES PROPRIETARY
1047        Not for use or disclosure outside Bell Laboratories except by
1048     written approval of the director of the distributing organization.
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060                                   - 16 -
1061
1062
1063
1064        Assignment  to  fixed  sized  variables  provides one way to
1065        generate  a  substring  consisting  of  a  fixed  number  of
1066        characters  from  the  beginning  or end of a string.  Other
1067        methods are discussed later.
1068
1069        The attributes -u and -l, are used for upper case and  lower
1070        case  formatting  respectively.   Since it makes no sense to
1071        have both attributes on simultaneously, turning on either of
1072        these attributes turns the other off.  The following script,
1073        using read and print which are described later, provides  an
1074        example of the use of shell variables with attributes.  This
1075        script reads a file of lines each consisting of five  fields
1076        separated  by  :  and prints fields 4 and 2 in upper case in
1077        columns 1-15,  left  justified,  and  columns  20-25  right-
1078        justified respectively.
1079
1080             typeset -uL15 f4                # 15 character left justified
1081             typeset -uR6 f2                 # 6 character right justified
1082             IFS=:                           # set field separator to :
1083             while   read -r f1 f2 f3 f4 f5  # read line, split into fields
1084             do      print -r -- "$f4  $f2"  # print fields 4 and 2
1085             done
1086
1087
1088        The -i,  -E,  and  -F,  attributes  are  used  to  represent
1089        numbers.   Each can be followed by a decimal number.  The -i
1090        attribute causes the value to be represented as  an  integer
1091        and  it can be followed by a number representing the numeric
1092        base when expanding its value.  Whenever a value is assigned
1093        to  an  integer  variable,  it is evaluated as an arithmetic
1094        expression and then truncated to an integer.
1095
1096        The -E attribute causes  the  value  to  be  represented  in
1097        scientific  notation  whenever  its  value is expanded.  The
1098        number following the -E determines the number of significant
1099        figures,  and  defaults  to  6.  The -F attribute causes the
1100        value to be represented with a fixed number of places  after
1101        the  decimal point. Assignments to variables of the -E or -F
1102        cause  the  evaluation  of  the  right  hand  side  of   the
1103        assignment.
1104
1105        ksh allows one-dimensional  arrays  in  addition  to  simple
1106        variables.   There  are  two  types  of  arrays; associative
1107        arrays and indexed arrays.  The subscript for an associative
1108        array  is  an arbitrary string, whereas the subscript for an
1109        indexed array is an arithmetic expression that is  evaluated
1110
1111
1112                       BELL LABORATORIES PROPRIETARY
1113        Not for use or disclosure outside Bell Laboratories except by
1114     written approval of the director of the distributing organization.
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126                                   - 17 -
1127
1128
1129
1130        to  yield  an  integer  index.   Any  variable can become an
1131        indexed array by referring to  it  with  a  subscript.   All
1132        elements  of an array need not exist.  Subscripts for arrays
1133        must evaluate to an  integer  between  0  and  some  maximum
1134        value,  otherwise  an  error results.  The maximum value may
1135        vary from one machine to  another  but  is  at  least  4095.
1136        Evaluation  of  subscripts is described in the next section.
1137        Attributes apply to the whole array.
1138
1139        Assignments to array variables can  be  made  to  individual
1140        elements  via  parameter  assignment commands or the typeset
1141        built-in.  Additionally, values can be assigned sequentially
1142        using the -A name option of the set command.  Referencing of
1143        subscripted variables requires the  character  $,  but  also
1144        requires  braces  around the array element name.  The braces
1145        are needed to avoid conflicts with the file name  generation
1146        mechanism.  The form of any array element reference is:
1147                            ${name[subscript]}.
1148        A subscript value of * or @ can  be  used  to  generate  all
1149        elements  of  an  array,  as  they are used for expansion of
1150        positional  parameters.   The  list  of  currently   defined
1151        subscripts  for  a  given  variable  can  be  generated with
1152        ${!name[@]}, or ${!name[*]}.
1153
1154        The nameref attribute causes the variable to be treated as a
1155        reference  to  the variable defined by its value.  Once this
1156        attribute is set, all references  to  this  variable  become
1157        references  to  the  variable  named  by  the  value of this
1158        variable.   For  example,  if  foo=bar,  then  setting   the
1159        reference   attribute   on  foo  will  call  all  subsequent
1160        references to foo to behave as references to bar.  Unsetting
1161        this  attribute breaks the association.  Reference variables
1162        are usually used inside functions whose  arguments  are  the
1163        name  of a shell variable. The names for reference variables
1164        cannot  contain  a  ..   Whenever  a   shell   variable   is
1165        referenced,  the  portion  of the variable up to the first .
1166        is checked to see whether it matches the name of a reference
1167        variable.   If  it  does,  then  the  name  of  the variable
1168        actually used consists of the concatenation of the  name  of
1169        the  variable  defined  by  the reference plus the remaining
1170        portion of the original variable name.  For  example,  using
1171        the predefined alias, alias nameref='typeset -n',
1172
1173             .bar.home.bam="hello world"
1174             nameref foo=.bar.home
1175             print ${foo.bam}
1176
1177
1178                       BELL LABORATORIES PROPRIETARY
1179        Not for use or disclosure outside Bell Laboratories except by
1180     written approval of the director of the distributing organization.
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192                                   - 18 -
1193
1194
1195
1196             hello world
1197
1198
1199        3.3  Substring Generation
1200
1201        The expansion of a variable or parameter can be modified  so
1202        that  only  a  portion  of  the  value  results. It is often
1203        necessary to extract a portion of  a  shell  variable  or  a
1204        portion  of an array.  There are several parameter expansion
1205        operators that can  do  this.   One  method  to  generate  a
1206        substring    is    with    an    expansion   of   the   form
1207        ${name:offset:length}  where   offset   is   an   arithmetic
1208        expression  that  defines  the offset of the first character
1209        starting from 0, and length is an arithmetic expression that
1210        defines the length of the substring.  If :length is omitted,
1211        the length of the value of name starting at offset is  used.
1212        The  :offset:length  operators  can also be applied to array
1213        expansions and to parameters * and @ to generate portions of
1214        an      array.       For     example,     the     expansion,
1215        ${name[@]:offset:length}, yields up to  length  elements  of
1216        the array name starting at the element offset.
1217
1218        The other parameter expansion modifiers use  shell  patterns
1219        to  describe portions of the string to modify and delete.  A
1220        description of shell  patterns  is  contained  below.   When
1221        these modifiers are applied to special parameters @ and * or
1222        to  array  parameters  given  as  name[@]  or  name[*],  the
1223        operation  is  performed  on  each  element.  There are four
1224        parameter substitution modifiers that strip off leading  and
1225        trailing   substrings   during   parameter  substitution  by
1226        removing  the  characters  matching  a  given  pattern.   An
1227        expansion  of  the  form ${name#pattern} causes the smallest
1228        matching prefix of the value of name  to  be  removed.   The
1229        largest  prefix  matching  pattern  is  removed  by using ##
1230        instead  of  #.   Similarly,  an  expansion  of   the   form
1231        ${name%pattern}  causes  the  smallest matching substring at
1232        the end of name to be removed.  Again, using %%  instead  of
1233        %,  causes  the  largest  matching  trailing substring to be
1234        deleted.  For example, if the shell variable file has  value
1235        foo.c, then the expression ${file%.c}.o has value foo.o.
1236
1237        The value of an expansion can be  changed  by  specifying  a
1238        pattern that matches the part that needs to be changed after
1239        the the parameter expansion modifier /.  An expansion of the
1240        form  ${name/pattern/string}  replaces  the  first  match of
1241        pattern with the value of  variable  name  to  string.   The
1242
1243
1244                       BELL LABORATORIES PROPRIETARY
1245        Not for use or disclosure outside Bell Laboratories except by
1246     written approval of the director of the distributing organization.
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258                                   - 19 -
1259
1260
1261
1262        second  /  is  not  necessary  when  string  is  null.   The
1263        expansion ${name//pattern/string} changes all occurrences of
1264        the  pattern into string.  The parameter expansion modifiers
1265        /# and /% cause the matching pattern to be anchored  to  the
1266        beginning and end respectively.
1267
1268        Finally, there are parameter expansion modifiers that yield,
1269        the  name of the variable, the string length of the value or
1270        the number of elements of an  array.   ${!name}  yields  the
1271        name  of  the variable which will be name itself except when
1272        name is a reference variable.  In this case  it  will  yield
1273        the name of the variable it refers to.  ${#name} will be the
1274        length in bytes of $name.  For an array variable ${#name[*]}
1275        gives the number of elements in the array.
1276
1277        3.4  Arithmetic Evaluation
1278
1279        For  the  most  part,  the  shell  is  a  string  processing
1280        language.   However,  the  need for arithmetic has long been
1281        obvious.  Many of the characters that  are  special  to  the
1282        Bourne  shell,  are needed as arithmetic operators.  To make
1283        arithmetic easy to use, and to maintain  compatibility  with
1284        the  Bourne  shell, ksh uses matching (( and )) to delineate
1285        arithmetic expressions.  While single parentheses might have
1286        been  more  desirable,  these  already mean subshell so that
1287        another notation was required.   The  arithmetic  expression
1288        inside  the  double  parentheses  follows  that same syntax,
1289        associativity and precedence as the  ANSI-C[15]  programming
1290        language.    The  characters  between  the  matching  double
1291        parentheses are processed  with  the  same  rules  used  for
1292        double  quotes so that spaces can be used to aid readability
1293        without additional quoting.
1294
1295        All  arithmetic  evaluations  are  performed  using   double
1296        precision   floating   point   arithmetic.   Floating  point
1297        constants follow the same rules as  the  ANSI-C  programming
1298        language.  Integer arithmetic constants are written as
1299                                base#number,
1300        where base is a decimal integer between two  and  sixty-four
1301        and  number  is  any  non-negative number.  Base ten is used
1302        when no base is specified.  The digits  are  represented  by
1303        the characters 0-9a-zA-Z_@.  For bases less than or equal to
1304        36,  upper  and  lower   case   characters   can   be   used
1305        interchangibly to represent the digits from 10 thru 35.
1306
1307
1308
1309
1310                       BELL LABORATORIES PROPRIETARY
1311        Not for use or disclosure outside Bell Laboratories except by
1312     written approval of the director of the distributing organization.
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324                                   - 20 -
1325
1326
1327
1328        Arithmetic expressions are made from  constants,  variables,
1329        operators.   Parentheses  may  be  used  for  grouping.  The
1330        contents inside the double parentheses  are  processed  with
1331        the  same expansions as occurs in a double quoted string, so
1332        that all $ expansions are performed  before  the  expression
1333        are  performed.   However,  there is no need to use the $ to
1334        get the value of a variable because the arithmetic evaluator
1335        replaces  the  name  of  the variable by its value within an
1336        arithmetic expression.   The  $  cannot  be  used  when  the
1337        variable  is  the  subject  of  assignment  or  an increment
1338        operation.  As a rule it is better not to use $ in front  of
1339        variables in an arithmetic expression.
1340
1341        An arithmetic command of the form (( ...  ))  is  a  command
1342        that  evaluates  the  enclosed  arithmetic  expression.  For
1343        example, the command
1344                                 (( x++ ))
1345        can be used to increment the variable  x,  assuming  that  x
1346        contains  some  numerical  value.  The arithmetic command is
1347        true (return value 0),  when  the  resulting  expression  is
1348        non-zero,  and  false  (return  value 1) when the expression
1349        evaluates to zero.  This makes the command easy to use  with
1350        the if and while compound command.
1351
1352        The for compound  command  has  been  extended  for  use  in
1353        arithmetic contexts. The syntax,
1354                       for (( expr1; expr2 ; expr3 ))
1355        can be used as the first line of a for loop  with  the  same
1356        semantics  as  the  for  statement in the ANSI-C programming
1357        language.
1358
1359        Arithmetic evaluations can also be performed as part of  the
1360        evaluation of a command line.  The syntax $(( ... )) expands
1361        to the value of the enclosed  arithmetic  expression.   This
1362        expansion   can   occur   wherever  parameter  expansion  is
1363        performed.   For  example  using  the  ksh   command   print
1364        (described later)
1365                               print $((2+2))
1366        prints the number 4.
1367
1368        The following  script  prints  the  first  n  lines  of  its
1369        standard  input  onto  its  standard  output, where n can be
1370        supplied as an optional argument whose default value is 20.
1371
1372             integer n=${1-20}                       # set n
1373             while   (( n-- >=0 )) && read -r line   # at most n lines
1374
1375
1376                       BELL LABORATORIES PROPRIETARY
1377        Not for use or disclosure outside Bell Laboratories except by
1378     written approval of the director of the distributing organization.
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390                                   - 21 -
1391
1392
1393
1394             do      print -r -- "$line"
1395             done
1396
1397
1398        3.5  Shell Expansions
1399
1400        The commands you enter from the terminal or  from  a  script
1401        are  divided  into  words  and  each  word undergoes several
1402        expansions to generate the command name and  its  arguments.
1403        This  is  done  in  two  phases.  The first phase recognizes
1404        reserved words, spaces and operators to decide where command
1405        boundaries  lie.  Alias substitutions take place during this
1406        phase.   The  second  phase  performs  expansions   in   the
1407        following order:
1408
1409           + Tilde  substitution,  parameter  expansion,  arithmetic
1410             expansion,  and command substitution are performed from
1411             left to right.
1412
1413           + The characters that result from parameter expansion and
1414             command   substitution   above  are  checked  with  the
1415             characters in  the  IFS  variable  for  possible  field
1416             splitting.  (See a description of read below to see how
1417             IFS is used.) Setting IFS to a null value causes  field
1418             splitting to be skipped.
1419
1420           + Pathname generation (as described below)  is  performed
1421             on  each of the fields.  Any field that doesn't match a
1422             pathname is left alone.  The option, -f or  noglob,  is
1423             used to disable pathname generation.
1424
1425        3.6  Pattern Matching
1426
1427        The shell is primarily a string processing language and uses
1428        patterns  for  matching  file  names as well as for matching
1429        strings.  The characters ?, *, and [ are processed specially
1430        by  the shell when not quoted.  These characters are used to
1431        form patterns that match strings.  Patterns are used by  the
1432        shell  to  match  pathnames,  to specify substrings, and for
1433        case commands.  The character ?  matches any one  character.
1434        The  character  *  matches  zero  or  more  characters.  The
1435        character sequence [...]  defines  a  character  class  that
1436        matches  any  character  contained  within  [].   A range of
1437        characters can be specified by putting a - between the first
1438        and  last  character  of the range.  An exclamation mark, !,
1439        immediately after the [, means match all  characters  except
1440
1441
1442                       BELL LABORATORIES PROPRIETARY
1443        Not for use or disclosure outside Bell Laboratories except by
1444     written approval of the director of the distributing organization.
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456                                   - 22 -
1457
1458
1459
1460        the   characters   specified.    For  example,  the  pattern
1461        a?c*.[!a-z] matches any string beginning with  an  a,  whose
1462        third  character  is a c, and that ends in .  (dot) followed
1463        by any character except the  lowercase  letters,  a-z.   The
1464        sequence [:alpha:] inside a character class, matches any set
1465        of  characters  in  the  ANSI-C  alpha  class.    Similarly,
1466        [:class:]  matches each of the characters in the given class
1467        for all the ANSI-C character classes.
1468
1469        ksh treats  strings  of  the  form  (pattern-list)  ,  where
1470        pattern-list  is a list of one or more patterns separated by
1471        a |, specially when preceded by *, ?,  +,  @,  or  !.   A  ?
1472        preceding   (pattern-list)   means  that  the  pattern  list
1473        enclosed in () is optional.  An @(pattern-list) matches  any
1474        pattern   in  the  list  of  patterns  enclosed  in  ().   A
1475        *(pattern-list) matches any string  that  contains  zero  or
1476        more  of  each  of the enclosed patterns, whereas +(pattern-
1477        list) requires a match of one or more of any  of  the  given
1478        patterns.   For  instance,  the pattern +([0-9])?(.) matches
1479        one or more digits  optionally  followed  by  a  .(dot).   A
1480        !(pattern-list)  matches  anything  except  any of the given
1481        patterns.  For example, print !(*.o) will display  any  file
1482        name that does not end in .o.
1483
1484        When patterns are used to generate pathnames when  expanding
1485        commands  several  other  rules  apply.  A separate match is
1486        made for each matching on each file name  component  of  the
1487        pathname. Read permission is required for any portion of the
1488        pathname that contains any special pattern character. Search
1489        permission  is  required for every component except possibly
1490        the last.
1491
1492        By default, file names in each directory that begin  with  .
1493        are  skipped  when performing a match.  If the pattern to be
1494        matched starts with a leading ., then only  files  beginning
1495        with  a  .,  are considered when finding matching files.  If
1496        the FIGNORE variable is set, then only  files  that  do  not
1497        match  this  pattern  are  considered.   This  overrides the
1498        special meaning of .  in a pattern and in a file name.
1499
1500        If the markdirs option is set, each matching  pathname  that
1501        is  the name of a directory has a trailing / appended to the
1502        name.
1503
1504
1505
1506
1507
1508                       BELL LABORATORIES PROPRIETARY
1509        Not for use or disclosure outside Bell Laboratories except by
1510     written approval of the director of the distributing organization.
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522                                   - 23 -
1523
1524
1525
1526        3.7  Conditional Expressions
1527
1528        The Bourne shell uses the test command, or the equivalent  [
1529        command,  to  test  the  attributes for files and to compare
1530        strings or numbers.  The problem with test is that the shell
1531        has  expanded  the  words of the test command and split them
1532        into arguments before test begins  execution.   test  cannot
1533        distinguish  between  operators and operands.  In most cases
1534        test "$1"  will  test  whether  argument  1   is   non-null.
1535        However,  if argument 1 is -f, then test will treat -f as an
1536        operator and yield a syntax error.  One of the most frequent
1537        errors  with  test  occurs  when its operands are not within
1538        double quotes.  In this case, the  argument  may  expand  to
1539        more  than  a  single argument or to no argument at all.  In
1540        either case this will likely cause  a  syntax  error.   What
1541        makes   this   most  insidious  is  that  these  errors  are
1542        frequently data dependent.  A script  that  appears  to  run
1543        correctly may abort if given unexpected data.
1544
1545        To get around these problems, ksh has a compound command for
1546        condition  expression  testing as part of the language.  The
1547        reserved words [[ and ]] delimit the range of  the  command.
1548        Because  they  are  reserved words, not operator characters,
1549        they require spaces to separate them  from  arguments.   The
1550        words  between  [[  and  ]]  are  not  processed  for  field
1551        splitting or for pathname generation.   In  addition,  since
1552        ksh  determines  the  operators  before parameter expansion,
1553        expansions that yield no argument  cause  no  problem.   The
1554        operators  within  [[...]]  are almost the same as those for
1555        the test command.  All  unary  operators  are  of  the  form
1556        -letter and are followed by a single operand.  Instead of -a
1557        and -o, [[...]] uses && and || to indicate "and"  and  "or".
1558        Parentheses are used without quoting for grouping.
1559
1560        The right hand side of the string  comparison  operators  ==
1561        and  !=  take  a  pattern  and  tests  whether the left hand
1562        operand matches this pattern.  Quoting the  pattern  results
1563        is  a  string  comparison rather than the pattern match. The
1564        operators < and > within [[...]]  designate  lexicographical
1565        comparison.
1566
1567        In  addition  there  are  several   other   new   comparison
1568        primitives.   The  binary  operators -ot and -nt compare the
1569        modification times of two files to see which file  is  older
1570        than or newer than the other.  The binary operator -ef tests
1571        whether two files have the same device  and  i-node  number,
1572
1573
1574                       BELL LABORATORIES PROPRIETARY
1575        Not for use or disclosure outside Bell Laboratories except by
1576     written approval of the director of the distributing organization.
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588                                   - 24 -
1589
1590
1591
1592        i. e., a link to the same file.
1593
1594        The unary operator -L returns  true  if  its  operand  is  a
1595        symbolic link.  The unary operator -O ( -G ) returns true if
1596        the owner (or group) of the file operand matches that of the
1597        caller.  The unary operator -o returns true when its operand
1598        is the name of an option that is currently on.
1599
1600        The  following  script  illustrates  some  of  the  uses  of
1601        [[...]].  The reference manual contains the complete list of
1602        operators.
1603
1604             for i in "${@}"
1605             do      # execute foo for numeric directory
1606                     if      [[ -d $i && $i == +([0-9]) ]]
1607                     then    foo
1608                     # otherwise if writable or executable file and not mine
1609                     elif    [[ (-w $i||-x $i) && ! -O $i ]]
1610                     then    bar
1611                     fi
1612             done
1613
1614
1615        3.8  Input and Output
1616
1617        ksh has extended I/O capabilities to enhance the use of  the
1618        shell  as a programming language.  As with the Bourne shell,
1619        you use the I/O redirection operator, <,  to  control  where
1620        input  comes  from,  and the I/O redirection operator, >, to
1621        control where output goes to. Each of these operators can be
1622        preceded  with  a  single  digit  that specifies a file unit
1623        number to associate with the file  stream.   Ordinarily  you
1624        specify  these  I/O  redirection  operators  with a specific
1625        command to which it applies.  However, if  you  specify  I/O
1626        redirections  with  the  exec  command,  and  don't  specify
1627        arguments to exec, then the I/O redirection applies  to  the
1628        current  program.   For  example,  the command exec < foobar
1629        opens file foobar for reading.  The  exec  command  is  also
1630        used  to  close files.  A file descriptor unit can be opened
1631        as a copy of an  existing  file  descriptor  unit  by  using
1632        either  of  the  <&  or  >&  operators  and putting the file
1633        descriptor unit of the original file  after  the  &.   Thus,
1634        2>&1 means open standard error (file descriptor 2) as a copy
1635        of standard output (file descriptor 1).  A  file  descriptor
1636        value  of  -  after  the & indicates that the file should be
1637        closed.  To close file unit 5, specify exec 5<&-.  There are
1638
1639
1640                       BELL LABORATORIES PROPRIETARY
1641        Not for use or disclosure outside Bell Laboratories except by
1642     written approval of the director of the distributing organization.
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654                                   - 25 -
1655
1656
1657
1658        two  additional redirection operators with ksh and the POSIX
1659        shell that are  not  part  of  the  Bourne  shell.   The  >|
1660        operator  overrides  the  effect  of  the  noclobber  option
1661        described earlier.  The <> operator  causes  a  file  to  be
1662        opened for both reading and writing.
1663
1664        ksh recognizes certain pathnames and treats them  specially.
1665        Pathnames of the form /dev/fd/n are treated as equivalent to
1666        the file defined by file descriptor n.  These  name  can  be
1667        used  as  the  script  argument  to  ksh  and in conditional
1668        testing as described  above.   On  underlying  systems  that
1669        support  /dev/fd  in  the  file  system,  these names can be
1670        passed  to  other   commands.    Pathnames   of   the   form
1671        /dev/tcp/hostid/port and /dev/udp/hostid/port can be used to
1672        create tcp and udp connections  to  services  given  by  the
1673        hostid  number  and  port  number.   The  hostid  cannot use
1674        symbolic values. In practice these are  typically  generated
1675        by       command       substitution.       For      example,
1676        exec 5> /dev/tcp/$(service name) would open file  descriptor
1677        5  for sending messages to hostid and port number defined by
1678        the output of service name.
1679
1680        The Bourne shell has a built-in  command  read  for  reading
1681        lines  from standard input (file descriptor 0) and splitting
1682        it into fields based on the value of the IFS variable, and a
1683        command echo to write strings to standard output.  ( On some
1684        systems,  echo  is  not  a  built-in  command   and   incurs
1685        considerable  overhead  to  use.)  Unfortunately, neither of
1686        these commands is able to perform  some  very  basic  tasks.
1687        For  example.   with  the  Bourne  shell,  the read built-in
1688        cannot read a single line that end in \.  With ksh the  read
1689        built-in has a -r option to remove the special meaning for \
1690        which allows it to be treated as a regular character  rather
1691        than  the  line  continuation  character.   With  the Bourne
1692        shell, there is no simple way to have  more  than  one  file
1693        open  at  any time for reading.  ksh has options on the read
1694        command to specify the file descriptor for the  input.   The
1695        fields  that  are  read  from  a  line can be stored into an
1696        indexed array with the -A option to  read.   This  allows  a
1697        line to be split into an arbitrary number of fields.
1698
1699        The way the Bourne shell uses  the  IFS  variable  to  split
1700        lines  into  fields  greatly limits its utility.  Often data
1701        files consist of lines that use a character  such  as  :  to
1702        delimit  fields  with  two adjacent delimiters that denote a
1703        null field.  The Bourne shell treats adjacent delimiters  as
1704
1705
1706                       BELL LABORATORIES PROPRIETARY
1707        Not for use or disclosure outside Bell Laboratories except by
1708     written approval of the director of the distributing organization.
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720                                   - 26 -
1721
1722
1723
1724        a  single  field  delimiter.   With ksh, delimiters that are
1725        considered white space characters have the behavior  of  the
1726        Bourne  shell,  but  other adjacent delimiters separate null
1727        fields.
1728
1729        The read command is often used in scripts that interact with
1730        the  user  by  prompting  the  user and then requesting some
1731        input.  With the Bourne shell two commands are  needed;  one
1732        to prompt the user, the other to read the reply.  ksh allows
1733        these two commands to be combined.  The  first  argument  of
1734        the read command can be followed by a ?  and a prompt string
1735        which is used whenever  the  input  device  is  a  terminal.
1736        Because the prompt is associated with the read built-in, the
1737        built-in command line editors will be able to re-output  the
1738        prompt  whenever the line needs to be refreshed when reading
1739        from a terminal device.
1740
1741        With the Bourne shell, there is no way to set a  time  limit
1742        for waiting for the user response to read.  The -t option to
1743        read takes a floating point argument that gives the time  in
1744        seconds,  or fractions of seconds that the shell should wait
1745        for a reply.
1746
1747        The version of the echo command in System V  treats  certain
1748        sequences beginning with \ as control sequences.  This makes
1749        it hard to output strings without interpretation.  Most  BSD
1750        derived  systems  do  not  interpret  \  control  sequences.
1751        Unfortunately, the BSD versions of echo accepts a -n  option
1752        to  prevent a trailing new-line, but has no way to cause the
1753        string -n to be  printed.   Neither  of  these  versions  is
1754        adequate.  Also,  because  they are incompatible, it is very
1755        hard to write portable shell scripts using  echo.   The  ksh
1756        built-in,  print, outputs characters to the terminal or to a
1757        file and subsumes the functions of  all  versions  of  echo.
1758        Ordinarily,  escape  sequences in arguments beginning with \
1759        are processed the same as for the  System  V  echo  command.
1760        However  print  follows the standard conventions for options
1761        and has options that make  print  very  versatile.   The  -r
1762        option  can  be  used  to  output  the arguments without any
1763        special meaning.  The -n option can be used here to suppress
1764        the  trailing new-line that is ordinarily appended.  As with
1765        read, it is possible to specify the file  descriptor  number
1766        as  an  option  to  the  command  to  avoid  having  to  use
1767        redirection operators with each occurrence of the command.
1768
1769
1770
1771
1772                       BELL LABORATORIES PROPRIETARY
1773        Not for use or disclosure outside Bell Laboratories except by
1774     written approval of the director of the distributing organization.
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786                                   - 27 -
1787
1788
1789
1790        The IEEE POSIX shell and utilities  standard  committee  was
1791        unable to reconcile the differences between the System V and
1792        BSD versions of echo.  They introduced a new  command  named
1793        printf  which  takes  an  ANSI-C format string and a list of
1794        options and outputs the strings using the ANSI-C  formatting
1795        rules.   Since  ksh  is POSIX conforming, it accepts printf.
1796        However, there is a -f options to print that can be used  to
1797        specify  a  format  string which processes the arguments the
1798        same way that printf does.
1799
1800        The format processing for print and printf has been extended
1801        slightly.  There are three additional formatting directives.
1802        The %b format causes the \ escape sequences to  be  expanded
1803        as  they  are with the System V echo command.  The %q format
1804        causes quotes to be placed on the output as required so that
1805        it  can  be  used as shell input.  Special characters in the
1806        output of most ksh built-in commands and in the output  from
1807        an  execution trace are quoted in an equivalent fashion. The
1808        %P format causes an extended regular expression string to be
1809        converted  into a shell pattern.  This is useful for writing
1810        shell applications that have to accept regular expression as
1811        input.  Finally, the escape sequence \E which expands to the
1812        terminal escape character (octal 033) has been added.
1813
1814        The shell is frequently used as a programming  language  for
1815        interactive  dialogues.  The select statement has been added
1816        to the language to make it easier to present menu  selection
1817        alternatives  to  the user and evaluate the reply.  The list
1818        of alternatives is numbered and  put  in  columns.   A  user
1819        settable  prompt,  PS3,  is  issued  and  if the answer is a
1820        number corresponding to one of the alternatives, the  select
1821        loop  variable is set to this value.  In any case, the REPLY
1822        variable is used to store the user entered reply.  The shell
1823        variables  LINES  and COLUMNS are used to control the layout
1824        of select lists.
1825
1826        3.9  Co-process
1827
1828        ksh can spawn a co-process by adding a |& after  a  command.
1829        This  process  will  be  run with its standard input and its
1830        standard  output  connected  to  the  shell.   The  built-in
1831        command  print  with  the  -p  option  will  write  into the
1832        standard input of this process and the built-in command read
1833        with  the  -p  option  will  read  from  the  output of this
1834        process.
1835
1836
1837
1838                       BELL LABORATORIES PROPRIETARY
1839        Not for use or disclosure outside Bell Laboratories except by
1840     written approval of the director of the distributing organization.
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852                                   - 28 -
1853
1854
1855
1856        In addition, the I/O redirection operators <& and >& can  be
1857        used to move the input or output pipe of the co-process to a
1858        numbered file descriptor.  Use exec 3>& p to move the  input
1859        of  the  co-process  to  file  descriptor 3.  After you have
1860        connected to file descriptor 3, you can direct the output of
1861        any command to the co-process by running command >&3.  Also,
1862        by  moving  the  input  of  the  co-process  to  a  numbered
1863        descriptor,  it is possible to run a second co-process.  The
1864        output of both co-processes  will  be  the  file  descriptor
1865        associated with read -p.  You can use exec 4< p to cause the
1866        output of these co-processes to go to file descriptor  4  of
1867        the shell.  Once you have moved the pipe to descriptor 4, it
1868        is possible to connect a server to the co-process by running
1869        command 4<& p   or   to   close  the  co-process  pipe  with
1870        exec 4<& -.
1871
1872        3.10  Functions
1873
1874        Function definitions are of the form
1875
1876             function name
1877             {
1878             any shell script
1879             }
1880
1881        A function whose name contains a .  is called  a  discipline
1882        function.   The  portion of the name before the last .  must
1883        refer to the name of an existing variable.  Thus, if p is  a
1884        reference to PATH, then the function name p.get and PATH.get
1885        refer to the same function.
1886
1887        The function is invoked either by  specifying  name  as  the
1888        command  name  and optionally following it with arguments or
1889        by using it  as  an  option  to  the  .   built-in  command.
1890        Positional  parameters  are  saved before each function call
1891        and restored when completed.  The arguments that follow  the
1892        function   name   on  the  calling  line  become  positional
1893        parameters inside the function.  The return built-in can  be
1894        used  to  cause  the  function  to  return  to the statement
1895        following the point of invocation.
1896
1897        Functions can also be defined with the System V notation,
1898
1899             name ()
1900             {
1901             any shell script
1902
1903
1904                       BELL LABORATORIES PROPRIETARY
1905        Not for use or disclosure outside Bell Laboratories except by
1906     written approval of the director of the distributing organization.
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918                                   - 29 -
1919
1920
1921
1922             }
1923
1924        Functions defined with this syntax cannot  be  used  as  the
1925        first  argument to a . procedure.  ksh accepts this notation
1926        for compatibility only.   There  is  no  need  to  use  this
1927        notation when writing ksh scripts.
1928
1929        Functions defined with the function name syntax and  invoked
1930        by  name  are  executed in the current shell environment and
1931        can  share  named  variables  with  the   calling   program.
1932        Options,  other  than execution trace -x, set by the calling
1933        program are passed down to a function.  The options are  not
1934        shared  with  the  function so that any options set within a
1935        function  are  restored  when  the  function  exits.   Traps
1936        ignored  by  the  caller are ignored within the function and
1937        cannot be enabled.  Traps caught by the calling program  are
1938        reset  to  their  default action with the function.  In most
1939        instances, the default action is to cause  the  function  to
1940        terminate.   A  trap  on  EXIT,  defined  within  a function
1941        executes after the function completes but before the  caller
1942        resumes.    Therefore,  any  variable  assignments  and  any
1943        options set as part of a trap action will be effective after
1944        the caller resumes.
1945
1946        By default, variables are  inherited  by  the  function  and
1947        shared  by  the  calling  program.   However,  for functions
1948        defined with the function name syntax that  are  invoked  by
1949        name,  environment substitutions preceding the function call
1950        apply only  to  the  scope  of  the  function  call.   Also,
1951        variables  whose  names do not contain a .  that are defined
1952        with the typeset built-in command are local to the  function
1953        that they are declared in.  Thus, for the function defined
1954
1955             function  name
1956             {
1957                  typeset -i x=10
1958                  let z=x+y
1959                  print $z
1960             }
1961
1962        invoked as y=13 name, x  and  y  are  local  variables  with
1963        respect to the function name while z is global.
1964
1965        Functions defined with  the  name()  syntax,  and  functions
1966        invoked  as  an argument to the .  command, share everything
1967        other  than   positional   parameters   with   the   caller.
1968
1969
1970                       BELL LABORATORIES PROPRIETARY
1971        Not for use or disclosure outside Bell Laboratories except by
1972     written approval of the director of the distributing organization.
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984                                   - 30 -
1985
1986
1987
1988        Assignments that precede the call remain in effect after the
1989        function completes.
1990
1991        Alias and function  names  are  not  passed  down  to  shell
1992        scripts  or carried across separate invocations of ksh.  The
1993        $FPATH variable gives a colon separated list of  directories
1994        that  is  searched  for  function definitions when trying to
1995        resolve the command name.  Whenever a file name contained in
1996        $FPATH is found, the complete file is read and all functions
1997        contained within become defined.
1998
1999        Calls that reference functions can be recursive.  Except for
2000        special  built-ins,  function  names  take  precedence  over
2001        built-in names and names of programs when  used  as  command
2002        names.  To write a function to replace a built-in command or
2003        to replace a program, you  must  use  the  command  built-in
2004        command.    The  arguments  to  command  are  the  name  and
2005        arguments of the program you want to execute.   For  example
2006        to  write  a  cd  function  which  changes the directory and
2007        prints out the directory name, you can write,
2008
2009             function  cd
2010             {
2011                  if      command cd  "$@"
2012                  then    print  -r -- $PWD
2013                  fi
2014             }
2015
2016
2017        The FPATH variable is a colon separated list that  ksh  uses
2018        to  search for function definitions.  When ksh encounters an
2019        autoload function, it runs the  .   command  on  the  script
2020        containing the function, and then executes the function.
2021
2022        Function definitions may also be placed  in  the  ENV  file.
2023        However,  this  causes  the  shell  to  take longer to begin
2024        executing.
2025
2026        3.11  Process Substitution
2027
2028        This feature is only  available  on  versions  of  the  UNIX
2029        operating  system  which  support  the /dev/fd directory for
2030        naming open  files.   Each  command  argument  of  the  form
2031        <(list)  or  >(list)  will  run  process list asynchronously
2032        connected to some file in the /dev/fd directory.   The  name
2033        of  this  file  will become the argument to the command.  If
2034
2035
2036                       BELL LABORATORIES PROPRIETARY
2037        Not for use or disclosure outside Bell Laboratories except by
2038     written approval of the director of the distributing organization.
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050                                   - 31 -
2051
2052
2053
2054        the form with > is selected then writing on this  file  will
2055        provide  input for list.  If < is used, then the file passed
2056        as an argument will contain the output of the list  process.
2057        For example,
2058
2059             paste  <(cut -f1 file1)  <(cut -fB file2) | tee >(process1)  >(process2)
2060
2061        extracts fields 1 and 3  from  the  files  file1  and  file2
2062        respectively,  places the results side by side, and sends it
2063        to the processes process1 and process2, as well  as  putting
2064        it  onto  the  standard output.  Note that the file which is
2065        passed as an argument  to  the  command  is  a  UNIX  system
2066        pipe(2)  so that the programs that expect to lseek(2) on the
2067        file will not work.
2068
2069        3.12  Finding Commands
2070
2071        The addition of aliases, functions, and more  built-ins  has
2072        made  it  substantially  more difficult to know what a given
2073        command word really means.
2074
2075        There are several reasons that commands are built  into  the
2076        shell  rather  than  being separate programs.  Commands that
2077        begin with reserved words are an integral part of the  shell
2078        language itself and typically define the control flow of the
2079        language.  Some control flow commands are not reserved words
2080        in  the  language but are special built-ins.  Special built-
2081        ins are built-ins that are considered a part of the language
2082        rather  than  user definable commands.  The best examples of
2083        commands that fit this description are break  and  continue.
2084        Because  they are not reserved words, they can be the result
2085        of shell expansions and are not effected by  quoting.  These
2086        commands have the following special properties:
2087
2088           + Assignments that precede  them  apply  to  the  current
2089             shell process, not just to the given command.
2090
2091           + An error in the format of these commands cause a  shell
2092             script or function that contains them to abort.
2093
2094           + They cannot be overridden by shell functions.
2095
2096        Other  commands  are  built-in  because  they  perform  side
2097        effects  on  the  current  environment  that would be nearly
2098        impossible to implement otherwise.  Built-ins such as cd and
2099        read  are  examples  of such built-ins.  These built-ins are
2100
2101
2102                       BELL LABORATORIES PROPRIETARY
2103        Not for use or disclosure outside Bell Laboratories except by
2104     written approval of the director of the distributing organization.
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116                                   - 32 -
2117
2118
2119
2120        semantically equivalent to commands that  are  not  built-in
2121        except that they don't take a path search to locate.
2122
2123        A third reason to have a command built-in is so that it will
2124        be  unaffected  by  the  setting  of the PATH variable.  The
2125        print  command fits this category.  Scripts that  use  print
2126        will be portable to all sites that run ksh.
2127
2128        The final reason for having a command be a built-in  is  for
2129        performance.   On  most  systems it is more than an order of
2130        magnitude faster to initiate a command that is built-in than
2131        to  create  a  separate process to run the command.  Example
2132        that fit this category are test and basename.
2133
2134        Given a command name ksh decides what  it  means  using  the
2135        following order:
2136
2137           + Reserved words define commands that form  part  of  the
2138             shell grammar.  They cannot be quoted.
2139
2140           + Alias substitutions occur first as part of the  reading
2141             of  commands.   Using  quotes  in the command name will
2142             prevent alias substitutions.
2143
2144           + Special built-ins come next.
2145
2146           + Functions.
2147
2148           + Commands that are built-in that are not associated with
2149             a pathname.
2150
2151           + If the command name contains a /, the program or script
2152             corresponding to the given name is executed.
2153
2154           + A path search locates the pathname corresponding to the
2155             command.  If the pathname where it is found matches the
2156             pathname  associated  with  a  built-in  command,   the
2157             built-in  command  is executed.  If the directory where
2158             the command is found is listed in the  FPATH  variable,
2159             the  file is read into the shell like a dot script, and
2160             a function by that name is invoked.  Once a pathname is
2161             found,  ksh  remembers  its  location  and  only checks
2162             relative directories in PATH the next time the  command
2163             name  is used.  Assigning a value to PATH causes ksh to
2164             forget the location of all command names.
2165
2166
2167
2168                       BELL LABORATORIES PROPRIETARY
2169        Not for use or disclosure outside Bell Laboratories except by
2170     written approval of the director of the distributing organization.
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182                                   - 33 -
2183
2184
2185
2186           + The FPATH variable is  searched  and  files  found  are
2187             treated as described above.
2188
2189        The  first  argument  of  the  command  built-in,  described
2190        earlier,  skips  the  checks  for  reserved  words  and  for
2191        function definitions.  In all other  ways,  command  behaves
2192        like  a built-in that is not associated with a pathname.  As
2193        a result, if the first argument  of  command  is  a  special
2194        built-in,  the  special  properties  of this built-in do not
2195        apply. For example, whereas, exec 3< foo will cause a script
2196        containing    it    to    abort    if    the   open   fails,
2197        command exec 3< foo results in a non-zero  exit  status  but
2198        does not abort the script.
2199
2200        You can get a complete list of the special built-in commands
2201        with builtin -s. In addition builtin without arguments gives
2202        a list of the current built-ins and the pathname  that  they
2203        are  associated  with.   A  built-in can be bound to another
2204        pathname by giving  the  pathname  for  the  built-in.   The
2205        basename  of  this  path  must  be  the  name of an existing
2206        built-in for this to succeed.  Specifying the  name  of  the
2207        built-in without a pathname causes this built-in to be found
2208        before a path search.  On systems with run time  loading  of
2209        libraries,  built-in  commands can be added with the builtin
2210        command.  Each command  that  is  to  be  built-in  must  be
2211        written  as  a  C function whose name is of the form b_name,
2212        where name is the name of the built-in that is to be  added.
2213        The  function  has  the  same argument calling convention as
2214        main.  The lower eight bits of the return value  become  the
2215        exit  status  for  this  built-in.   Builtins  are  added by
2216        specifying the pathname of the library as an argument to the
2217        -f option of builtin.
2218
2219        A built-in command, whence, when used with the -v option has
2220        been  provided  to  answer this question.  A line is printed
2221        for each argument to whence telling  what  would  happen  if
2222        this  argument  were  used as a command name.  It reports on
2223        reserved words, aliases, built-ins, and functions.   If  the
2224        command  is  none  of  the above, it follows the path search
2225        rules and prints the full path-name, if  any,  otherwise  it
2226        prints an error message.
2227
2228
2229
2230
2231
2232
2233
2234                       BELL LABORATORIES PROPRIETARY
2235        Not for use or disclosure outside Bell Laboratories except by
2236     written approval of the director of the distributing organization.
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248                                   - 34 -
2249
2250
2251
2252        3.13  Symbolic Names
2253
2254        To  avoid  implementation  dependencies,  ksh  accepts   and
2255        generates  symbolic  names  for built-ins that use numerical
2256        values in the Bourne shell.  The  -S  option  of  the  umask
2257        built-in  command accepts and displays default file creation
2258        permissions  symbolically.   It  uses  the   same   symbolic
2259        notation as the chmod command.
2260
2261        The trap and kill built-in commands allows the signal  names
2262        to  be  given  symbolically.  The names of signals and traps
2263        corresponding to signals are the same  as  the  signal  name
2264        with the SIG prefix removed.  The trap 0 is named EXIT.
2265
2266        3.14  Added Traps
2267
2268        A new trap named ERR has been added.  This trap  is  invoked
2269        whenever  the  shell  would  exit if the -e option were set.
2270        This trap is used by Fourth Generation Make[16]  which  runs
2271        ksh as a co-process.
2272
2273        A trap named DEBUG gets executed after each  command.   This
2274        trap can be used for debugging purposes.  The KEYBD trap was
2275        described earlier.
2276
2277        3.15  Debugging
2278
2279        The primary method for debugging Bourne shell scripts is  to
2280        use  the -x option to enable the execution trace.  After all
2281        the expansions have been performed, but before each  command
2282        is executed, the trace writes to standard error the name and
2283        arguments of each command preceded by a +.  With ksh the PS4
2284        variable  is  evaluated  for  parameter  substitution and is
2285        displayed before each command, instead of the +.
2286
2287        The LINENO variable  is  set  to  the  current  line  number
2288        relative to the beginning of the current script or function.
2289        It is most useful as part of the PS4 prompt.
2290
2291        The variable  RANDOM produces a random number in the range 0
2292        to  32767  each  time  it is referenced.  Assignment to this
2293        variable sets the seed for the random number generator.
2294
2295        The parameter  PPID is used to generate the  process  id  of
2296        the process which invoked this shell.
2297
2298
2299
2300                       BELL LABORATORIES PROPRIETARY
2301        Not for use or disclosure outside Bell Laboratories except by
2302     written approval of the director of the distributing organization.
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314                                   - 35 -
2315
2316
2317
2318        3.16  Timing Commands
2319
2320        A reserved word time has been  added  to  replace  the  time
2321        command.   Any function, command or pipeline can be preceded
2322        by this  reserved  word  to  obtain  information  about  the
2323        elapsed,  user,  and  system  times.  Since I/O redirections
2324        bind to the command, not to time, parentheses should be used
2325        to redirect the timing information which is normally printed
2326        on file descriptor 2.
2327
2328
2329        4.  SECURITY
2330
2331        There are several documented problems  associated  with  the
2332        security of  shell  procedures[17].   These  security  holes
2333        occur   primarily   because   a   user  can  manipulate  the
2334        environment  to  subvert  the  intent  of  a  setuid   shell
2335        procedure.   Frequently, shell procedures are initiated from
2336        binary programs, without the author's awareness, by  library
2337        routines which invoke shells to carry out their tasks.  When
2338        the binary program is run setuid then  the  shell  procedure
2339        runs  with  the  permissions  afforded  to  the owner of the
2340        binary file.
2341
2342        In the Bourne shell, the IFS parameter is used to split each
2343        word  into separate command arguments.  If a user knows that
2344        some setuid program will run sh -c /bin/pwd  (or  any  other
2345        command  in  /bin)  then  the  user  sets and exports IFS=/.
2346        Instead of running /bin/pwd the shell will run bin with  pwd
2347        as  an  argument.   The user puts his or her own bin program
2348        into the current directory.  This program can create a  copy
2349        of  the  shell,  make  this  shell  setuid, and then run the
2350        /bin/pwd program so that the original program  continues  to
2351        run  successfully.  This kind of penetration is not possible
2352        with ksh since the IFS parameter only splits arguments  that
2353        result from command or parameter substitution.
2354
2355        Some setuid programs run  programs  using  system()  without
2356        giving  the  full  pathname.   If  the  user  sets  the PATH
2357        variable so that the desired command will be found in his or
2358        her  local  bin, then the same technique described above can
2359        be employed to compromise the security of  the  system.   To
2360        close  up  this  and  other  security  holes, ksh resets the
2361        effective user id to the real  user  id  and  the  effective
2362        group  id  to the real group id unless the privileged option
2363        (-p)  is  specified  at  invocation.   In  this  mode,   the
2364
2365
2366                       BELL LABORATORIES PROPRIETARY
2367        Not for use or disclosure outside Bell Laboratories except by
2368     written approval of the director of the distributing organization.
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380                                   - 36 -
2381
2382
2383
2384        privileged   mode,  the  .profile  and  ENV  files  are  not
2385        processed.  Instead, the file /etc/suid_profile is read  and
2386        executed.   This  gives  an  administrator  control over the
2387        environment to set the PATH variable or to log setuid  shell
2388        invocations.   Clearly security of the system is compromised
2389        if /etc or this file is publicly writable.
2390
2391        In the Berkeley UNIX version the operating system looks  for
2392        the  characters  #!   as  the  first  two  characters  of an
2393        executable file.  If these characters are  found,  then  the
2394        next word on this line is taken as the interpreter to invoke
2395        for this command and the interpreter is execed with the name
2396        of  the  script  as  argument zero and argument one.  If the
2397        setuid or setgid  bits  are  on  for  this  file,  then  the
2398        interpreter  is  run  with  the effective uid and/or gid set
2399        accordingly.  This scheme has two major drawbacks.  First of
2400        all,   using   the  #!   notation  forces  an  exec  of  the
2401        interpreter  even  when  the  call  is  invoked   from   the
2402        interpreter  which  it must exec.  This is inefficient since
2403        the interpreter can handle a failed exec  much  faster  than
2404        starting  up  again.   More  importantly,  setuid and setgid
2405        procedures provide an easy target for intrusion.  By linking
2406        a  setuid  or  setgid procedure to a name beginning with a -
2407        the interpreter is fooled into thinking  that  it  is  being
2408        invoked with a command line option rather than the name of a
2409        file.  When the interpreter is the shell, the  user  gets  a
2410        privileged interactive shell.  There is code in ksh to guard
2411        against this simple form of intrusion.
2412
2413        A more reliable way to handle setuid and  setgid  procedures
2414        is  provided  with  ksh.  The technique does not require any
2415        changes  to  the  operating  system  and   provides   better
2416        security.   Another advantage to this method is that it also
2417        allows scripts which have execute  permission  but  no  read
2418        permission  to  run.   Taking  away  read  permission  makes
2419        scripts more secure.
2420
2421        The method relies on a setuid root program  to  authenticate
2422        the request and exec the shell with the correct mode bits to
2423        carry  out  the  task.   This  shell  is  invoked  with  the
2424        requested  file  already  open  for reading.  A script which
2425        cannot be opened for reading or which has its setuid  and/or
2426        setgid bits turned on causes this setuid root program to get
2427        execed.  For security reasons, this  program  is  given  the
2428        full   pathname   /etc/suid_exec.    A  description  of  the
2429        implementation of the /etc/suid_exec program can be found in
2430
2431
2432                       BELL LABORATORIES PROPRIETARY
2433        Not for use or disclosure outside Bell Laboratories except by
2434     written approval of the director of the distributing organization.
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446                                   - 37 -
2447
2448
2449
2450        a separate paper[18].
2451
2452
2453        5.  CODE CHANGES
2454
2455        ksh is written in ANSI-C as a reusable  library.   The  code
2456        can  be compiled with C++ and older K&R C as well.  The code
2457        uses the IEEE  POSIX  1003.1  and  ISO  9945-1  standard[19]
2458        wherever  possible  so that ksh should be able to run on any
2459        POSIX compliant system.  In  addition,  it  is  possible  to
2460        compile ksh for older systems.
2461
2462        Unlike earlier version of the Bourne shell, ksh treats eight
2463        bit  characters  transparently  without  stripping  off  the
2464        leading bit.  There is also a compile time switch to  enable
2465        handling multi-byte and multi-width characters sets.
2466
2467        On systems with dynamic libraries, it  is  possible  to  add
2468        built-in  commands  at  run  time  with the built-in command
2469        builtin described earlier.  It is also possible to embed ksh
2470        in applications in a manner analogous to tcl.
2471
2472
2473        6.  EXAMPLE
2474
2475        An example of a ksh script  is  included  in  the  Appendix.
2476        This  one  page  program  is  a  variant  of the UNIX system
2477        grep(1) program.  Pattern matching for this version of  grep
2478        means shell patterns.
2479
2480        The first half uses the getopts command to find  the  option
2481        flags.   Nearly  all  options  have  been  implemented.  The
2482        second half goes through each line of each file to look  for
2483        a pattern match.
2484
2485        This program is not intended to serve as a  replacement  for
2486        grep  which  has been highly tuned for performance.  It does
2487        illustrate the programming  power  of  ksh.   Note  that  no
2488        auxiliary  processes  are  spawned  by  this script.  It was
2489        written and debugged in under two hours.  While  performance
2490        is acceptable for small files, this program runs at only one
2491        tenth the speed of grep for large files.
2492
2493
2494
2495
2496
2497
2498                       BELL LABORATORIES PROPRIETARY
2499        Not for use or disclosure outside Bell Laboratories except by
2500     written approval of the director of the distributing organization.
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512                                   - 38 -
2513
2514
2515
2516        7.  PERFORMANCE
2517
2518        ksh executes many scripts faster than the  System  V  Bourne
2519        shell;  in  some  cases  more  than  10  times as fast.  The
2520        primary reason for this is that ksh creates fewer processes.
2521        The  time to execute a built-in command or a function is one
2522        or two orders of magnitude faster than performing  a  fork()
2523        and   exec()   to   create   a  separate  process.   Command
2524        substitution and commands inside parentheses  are  performed
2525        without   creating  another  process,  unless  necessary  to
2526        preserve correct behavior.
2527
2528        Another reason for improved performance is the  use  of  the
2529        sfio[20], library for I/O.  The sfio library buffers all I/O
2530        and  output and buffers are flushed only when required.  The
2531        algorithms used in  sfio  perform  better  than  traditional
2532        versions of standard I/O so that programs that spend most of
2533        their time formatting output  may  actually  perform  better
2534        than versions written in C.
2535
2536        Several of the internal algorithms have been changed so that
2537        the  number  of  subroutine  calls  has  been  substantially
2538        reduced.  ksh uses variable sized hash tables for variables.
2539        Scripts  that  rely heavily on referencing variables execute
2540        faster.  More processing  is  performed  while  reading  the
2541        script  so that execution time is saved while running loops.
2542        These changes are not noticeable for scripts that fork() and
2543        run  processes,  but  they  reduce the time that it takes to
2544        interpret commands by more than a factor of two.
2545
2546        Most  importantly,   ksh   provide   mechanisms   to   write
2547        applications  that  do  not  require as many processes.  The
2548        arithmetic provided by the shell eliminates the need for the
2549        expr   command.    The   pattern   matching   and  substring
2550        capabilities eliminate the need to use sed or awk to process
2551        strings.
2552
2553        The architecture of ksh  makes  it  easy  to  make  commands
2554        built-ins  without  changing  the semantics at all.  Systems
2555        that have run-time binding of libraries  allow  applications
2556        to  be  sped  up by supplying the critical programs as shell
2557        built-in commands.  Implementations on other systems can add
2558        built-in commands at compile time.
2559
2560
2561
2562
2563
2564                       BELL LABORATORIES PROPRIETARY
2565        Not for use or disclosure outside Bell Laboratories except by
2566     written approval of the director of the distributing organization.
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578                                   - 39 -
2579
2580
2581
2582        8.  CONCLUSION
2583
2584        The 1988 version of ksh has tens  of  thousands  of  regular
2585        users  and  is  a suitable replacement for the Bourne shell.
2586        The 1993 version of ksh  is  essentially  upward  compatible
2587        with  both  the 1988 version of ksh and with the recent IEEE
2588        POSIX and ISO shell standard.  The 1993 version offers  many
2589        advantages  for  programming  applications,  and it has been
2590        rewritten so that it can be used in  embedded  applications.
2591        It also offers improved performance.
2592
2593
2594
2595        MH-11267-DGK-dgk              David G. Korn
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630                       BELL LABORATORIES PROPRIETARY
2631        Not for use or disclosure outside Bell Laboratories except by
2632     written approval of the director of the distributing organization.
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644                                   - 40 -
2645
2646
2647
2648                                  APPENDIX
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696                       BELL LABORATORIES PROPRIETARY
2697        Not for use or disclosure outside Bell Laboratories except by
2698     written approval of the director of the distributing organization.
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710                                   - 41 -
2711
2712
2713
2714
2715                                 References
2716
2717
2718
2719         1. S. R. Bourne, An Introduction to the UNIX Shell," BSTJ -
2720            Vol. 57, No. 6 part 2, pages 1947-1972.
2721
2722         2. POSIX  -  Part  2: Shell and Utilities, IEEE Std 1003.2-
2723            1992, ISO/IEC 9945-2:1992.
2724
2725         3. Al Aho, Brian Kernighan, and Peter Weinberger,  The  AWK
2726            Programming Language, Addison Wesley, 1988.
2727
2728         4. LLoyd H. Nakatani and Laurence W.  Ruedisueli,  The  FIT
2729            Programming Language Primer, TN 1126-920301-03, 1992.
2730
2731         5. Larry Wall, The PERL Programming Language,
2732
2733         6. John K. Ousterhout, Tcl: An Embeddable Command Language,
2734            Proceedings of the USENIX meeting, pp. ?-?, 1990.
2735
2736         7. S. R. Bourne, An Introduction to the  UNIX  Shell,  Bell
2737            System  Technical  Journal,  Vol. 57, No. 6, Part 2, pp.
2738            1947-1972, July 1978.
2739
2740         8.   W.   Joy,   An  Introduction  to  the  C  Shell,  Unix
2741            Programmer's  Manual,  Berkeley  Software  Distribution,
2742            University of California, Berkeley, 1980.
2743
2744         9. Morris Bolsky and David Korn, The KornShell Command  and
2745            Programming Language, Prentice Hall, 1989.
2746
2747        10.  Jason  Levitt,  The  Korn  Shell: An Emerging Standard,
2748            UNIX/World, pp. 74-81, September 1986.
2749
2750        11.  Rich Bilancia, Proficiency and Power are Yours With the
2751            Korn Shell, UNIX/World, pp. 103-107, September 1987.
2752
2753        12.  John  Sebes, Comparing UNIX Shells, UNIX Papers, Edited
2754            by the Waite Group, Howard W. Sams & Co., 1987.
2755
2756        13. T. A. Dolotta and J. R. Mashey, Using  the  shell  as  a
2757            Primary  Programming  Tool,  Proc.  2nd.  Int.  Conf. on
2758            Software Engineering, 1976, pages 169-176.
2759
2760
2761
2762                       BELL LABORATORIES PROPRIETARY
2763        Not for use or disclosure outside Bell Laboratories except by
2764     written approval of the director of the distributing organization.
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776                                   - 42 -
2777
2778
2779
2780        14.  J.  S.  Pendergrast,  WKSH  - Korn Shell with X-Windows
2781            Support, USL.
2782
2783        15. American National Standard  for  Information  Systems  -
2784            Programming Language - C, ANSI X3.159-1989.
2785
2786        16. G. S. Fowler, "The Fourth Generation Make,"  Proceedings
2787            of the Portland USENIX meeting, pp. 159-174, 1985.
2788
2789        17.  F.  T.  Grampp  and R. H. Morris, UNIX Operating System
2790            Security, AT&T Bell Labs Tech. Journal, Vol. 63, No.  8,
2791            Part 2, pp.1649-1671, 1984.
2792
2793        18. D. G Korn Parlez-vous Kanji?  TM-59554-860602-03, 1986.
2794
2795        19. POSIX - Part 1: System  Application  Program  Interface,
2796            IEEE Std 1003.1-1990, ISO/IEC 9945-1:1990.
2797
2798        20.  David  Korn  and  Kiem-Phong  Vo,  SFIO  -  A Safe/Fast
2799            Input/Output library, Proceedings of the Summer  Usenix,
2800            pp. , 1991.
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828                       BELL LABORATORIES PROPRIETARY
2829        Not for use or disclosure outside Bell Laboratories except by
2830     written approval of the director of the distributing organization.
2831
2832
2833
2834
2835
2836
2837
2838