Le shell KSH

(résumé)

Voici un peu d'info sur le shell KSH, quelques définitions, des exemples etc.


Bibliographie:


Démarrage:


Variables principales:


Commandes générales:


Commandes de TEST:


Exercice numéro 1:

Détecter qu'un fichier dans le repertoire courant est bien un fichier normal.

Source:

#!/usr/bin/ksh

# teste le nb de paramètres

if [ $# -eq 1 ]

then

# teste le type du fichier

  if test -f $1

  then

    echo "OK"

  else

    echo "Mauvais type ou introuvable"

  fi

else

  echo "mauvais nombre de paramètres"

fi


Exercice numéro 2:

Ecrire un script qui:

Source:

#!/usr/bin/ksh

case $# in

  0)pwd;;

  1)if [ -f $1 ]

        then

          more $1

        else

          ls $1

    fi;;

  2)if [ -a $2 ]

        then

          echo $2 existe deja

        else

          echo cp $1 $2

    fi;;

  *);;

esac


Exercice numéro 3:

Ecrire un script qui écrit la chaîne passée en 1er argument dans un fichier temporaire autant de fois que nécessaire pour que la taille de ce fichier ne dépasse pas la valeur du 1er argument.

Source:

#!/usr/bin/ksh

>/tmp/temp.$$

echo Création de /tmp/temp.$$

if [ $# -eq 2 ]

then

  while [ `wc -c </tmp/temp.$$` -lt $2 ] 

  do

        echo $1 >>/tmp/temp.$$ 

  done

else

  echo "nombre d'arguments incorrect"

fi


Exercice numéro 4:

Écrire un script shell à 2 paramètres (le 1er est un repertoire) qui indique si la chaîne composée du 2eme argument et de l'une des extensions .o .h .c est le nom d'un fichier qui existe dans ce repertoire.

Source:

#!/usr/bin/ksh

if [ $# -eq 2 ]

then

        for mot in $2 $2.o $2.h $2.c

        do

                if [ -f $1/$mot ]

                then

                        echo $1/$mot existe

                else

                        echo $1/$mot n existe pas

                fi

        done

else

        echo "nombre d'arguments incorrect"

fi


Exercice numéro 6a:

Détecter si un processus tourne (nom ou numéro en parametre). "ps x" sur alpha et "ps -x" sur sun. Source:

#!/usr/bin/ksh

if [ $# -eq 1 ]

then

        /sbin/ps x | /sbin/grep $1 >/dev/null

        if [ 0 -eq $? ]

        then

                echo trouve

        else

                echo "non trouve"

        fi

else

  echo "un parametre necessaire"

fi


Exercice numéro 6b:

Même chose avec "&&" et "||". Source:

#!/usr/bin/ksh

if [ $# -eq 1 ]

then

           ps x | grep $1 | grep -v grep >/dev/null && echo trouve  || echo non trouve

else

  echo "un parametre necessaire"

fi


Exercice numéro 7:

Combien de processus d'un utilisateur tournent sur la machine? Source:

#!/usr/bin/ksh

# compte le nombre de lignes

ps aux | grep $1 | wc -l


Exercice numéro 8:

Lister le nom de tous les fichiers ordinaires éxécutables du répertoire donné en paramètre (si aucun paramètre affichier le répertiore courant). Source:

#!/usr/bin/ksh

## pour le separateur

IFS=:



for i in $PATH

do

        echo $i/$1

        if [ -f $i/$1 ] && [ -x $i/$1 ]

        then

                echo ======= $i/$1

        fi

done


Exercice numéro 9:

le fichier passé en paramètre est-il un fichier ordinaire éxécutable situé dans un des répertoires du $PATH ?

#!/usr/bin/ksh

## pour le separateur

IFS=:



for i in $PATH

do

        echo $i/$1

        if [ -f $i/$1 ] && [ -x $i/$1 ]

        then

                echo ======= $i/$1

        fi

done


Exercice numéro 10:

Á partir d'un répertoire donné en paramètre, parcourir l'arborescence en affichant les noms des fichiers ordinaires à tous les niveaux. Source:

#!/usr/bin/ksh

for i in $1/*

do

        if [ -f $i ]

        then

                echo fichier:    $i

        fi

        if [ -d $i ]

        then

                echo Listage du rep $i

                $0 $i

        fi

done


Exercice numéro 11:

#!/bin/ksh

# procedure qui doit recevoir au moins 3 parametres

# remplace "mot" par un autre dans les fichiers donnes en argument

# arguments:

# 1 : ancien mot

# 2 : nouveau mot

# 3.. : fichiers concernes



if [ $# -lt 3 ]

then

        echo 3 parametres minimum

        exit 1

fi



ancien=$1

nouveau=$2

shift 2

fichiers=$*



for i in $fichiers

do

        echo ---------- Traitement de $i

        sed -e '1,$s/'$ancien'/'$nouveau'/g' $i

done


MANUEL

KSH(1)                   USER COMMANDS                     KSH(1)

















NAME ksh - Bourne / Korn Shell (Public Domain)

SYNOPSIS ksh [-st] [-c command] [file [argument ...]]

INTRODUCTION This document only summarizes the System V, release 2 shell features. All of the System V features except for ``res- tricted mode'' are implemented. See also the BUGS section. Features of the Korn shell are described in more detail. Only a subset of the Korn shell features are currently implemented.

DESCRIPTION Command syntax The ``#'' character begins a one-line comment, unless the ``#'' occurs inside a word. The tokens ``;'', ``|'', ``&'', ``;;'', ``||'', ``&&'', ``('', and ``)'' stand by them- selves. A word is a sequence of any other non-whitespace characters, which may also contain quoted strings (quote character are ``''', ``"'', ```'', or a matching ``${ }'' or ``$( )'' pair). A name is an unquoted word made up of letters, digits, or ``_''. Any number of whitespace charac- ters (space and tab) may separate words and tokens. In the following syntax, { ... }? indicates an optional thing, { ... }* indicates zero or more repetitions, { ... | ... } indicates alternatives. statement: ( list ) { list ; } for name { in { word }* }? do list ; done { while | until } list ; do list ; done if list ; then list ; { elif list ; then list ; }* { else list ; }?fi case name in { ( word { | word } ) list ;; }* esac function name { list ; } name () { list ; } time pipe The opening parenthesis of the pattern is optional. Redirection may occur at the beginning or end of a statement. command: { name=word }* { word }* Redirection may occur anywhere in a command. list: cond Printed 9/14/93 January 1988 1 KSH(1) USER COMMANDS KSH(1) cond ; list cond & list cond: pipe pipe && cond pipe || cond pipe: statement { | statement }* Alias expansion Alias expansion occurs when the first word of a statement is a defined alias, except when that alias is already being expanded. It also occurs after the expansion of an alias whose definition ends with a space. Shell variables The following standard special variables exist: !, #, $, -, ?. _ In interactive use this parameter is set to the last word of the previous command. When a command is exe- cuted this parameter is set to the full path of the command and placed in the environment for the command. See also MAILPATH. CDPATH The search path for the cd command. ENV If this variable is set at start-up (after any profile files are executed), the expanded value is used as shell start-up file. It typically contains function and alias definitions. FCEDIT The editor used by the fc command. IFS Internal field separator, used during substitution and the read command. HOME The default directory for the cd command. MAIL If set, the user will be informed of the arrival of mail in the named file. This variable is ignored if the MAILPATH variable is set. MAILCHECK How often, in seconds, the shell will check for mail in the file(s) specified by MAIL or MAILPATH. If 0, the shell checks before each prompt. The default is 600 seconds. Printed 9/14/93 January 1988 2 KSH(1) USER COMMANDS KSH(1) MAILPATH A list of files to be checked for mail. The list is colon separated, and each file may be followed by a ? and a message to be printed if new mail has arrived. Command and parameter substitution is performed on the message, and the parameter $_ is set to the name of the file. The default message is ``you have mail in $_''. PATH The search path for executable commands and .'d files. PPID The process number of the parent of the shell. PS1 PS2 PS1 is the primary prompt for interactive shells. Dol- lar substitution is performed, and ! is replaced with the command number (see fc). PWD OLDPWD The current and previous working directories. RANDOM A random integer. The random number generator may be seeded by assigning an integer value to this variable. SECONDS The number of seconds since the shell timer was started or reset. Assigning an integer value to this variable resets the timer. Substitution In addition to the System Vr2 substitutions, the following are available. $(command) Like `command`, but no escapes are recognized. $(<file) Equivalent to $(cat file), but without forking. ${#var} The length of the string value of var, or the number of arguments if var is * or @. ${var#pattern} ${var##pattern} If pattern matches the beginning of the value of var, the matched text is deleted from the result of substi- tution. A single # results in the shortest match, two #'s results in the longest match. ${var%pattern} ${var%%pattern} Like # substition, but deleting from the end of the value. Printed 9/14/93 January 1988 3 KSH(1) USER COMMANDS KSH(1) Expressions Expressions can be used with the let command, as numeric arguments to the test command, and as the value of an assignment to an integer variable. Expression may contain alpha-numeric variable identifiers and integer constants and may be combined with the following operators: == != <= < > >= + - * / % ! ( ) Command execution After evaluation of keyword assignments and arguments, the type of command is determined. A command may execute a shell function, a shell built-in, or an executable file. Any keyword assignments are then performed according to the type of command. In function calls assignments are local to the function. Assignments in built-in commands marked with a - persist, otherwise they are temporary. Assignments in executable commands are exported to the sub-process execut- ing the command. Even on systems where the exec() family does not support #! notation for scripts, ksh can be configured to fake it. There are several built-in commands. : Only expansion and assignment are performed. This is the default if a command has no arguments. . file Execute the commands in file without forking. The file is searched in the directories of $PATH. Passing argu- ments is not implemented. alias [name=value ...] Without arguments, alias lists all aliases and their values. For any name without a value, its value is listed. Any name with a value defines an alias, see "Alias Expansion" above. Korn's tracked aliases are not implemented, but System V command hashing is (see "hash"). alias -d [name=value ...] Directory aliases for tilde expansion, eg. alias -d fac=/usr/local/usr/facilities cd ~fac/bin break [levels] builtin command arg ... Printed 9/14/93 January 1988 4 KSH(1) USER COMMANDS KSH(1) Command is executed as a built-in command. cd [path] Set the working directory to path. If the parameter CDPATH is set, it lists the search path for the direc- tory containing path. A null path means the current directory. If path is missing, the home directory ($HOME) is used. If path is -, the previous working directory is used. If path is .., the shell changes directory to the parent directory, as determined from the value of PWD. The PWD and OLDPWD variables are reset. cd old new The string new is substituted for old in the current directory, and the shell attempts to change to the new directory. continue [levels] echo ... Echo is replaced with the alias echo='print' in the Korn shell. eval command ... exec command arg ... The executable command is executed without forking. If no arguments are given, any IO redirection is per- manent. exit [status] fc [-e editor] [-lnr] [first [last]] First and last select commands. Commands can be selected by history number, or a string specifing the most recent command starting with that string. The -l option lists the command on stdout, and -n inhibits the default command numbers. The -r option reverses the order of the list. Without -l, the selected commands can be edited by the editor specified with the -e option, or if no -e is specified, the $FCEDIT editor, then executed by the shell. fc -e - [-g] [old=new] [command] Re-execute the selected command (the previous command by default) after performing the optional substitution of old with new. If -g is specified, all occurrences of old are replaced with new. This command is usually accessed with the predefined alias r=``fc -e -''. getopts Printed 9/14/93 January 1988 5 KSH(1) USER COMMANDS KSH(1) See the attached manual page. hash [-r] [name ...] Without arguments, any hashed executable command path- names are listed. The -r flag causes all hashed com- mands to be removed. Each name is searched as if it were a command name and added to the hash table if it is an executable command. kill [-signal] process ... Send a signal (TERM by default) to the named process. The signal may be specified as a number or a mnemonic from <signal.h> with the SIG prefix removed. let [expression ...] Each expression is evaluated, see "Expressions" above. A zero status is returned if the last expression evalu- ates to a non-zero value, otherwise a non-zero status is returned. Since may expressions need to be quoted, (( expr )) is syntactic sugar for let "expr". print [-nreun] [argument ...] Print prints its arguments on the standard output, separated by spaces, and terminated with a newline. The -n option eliminates the newline. By default, certain C escapes are translated. These include \b, \f, \n, \r, \t, \v, and \### (# is an octal digit). \c is equivalent to the -n option. This expansion may be inhibitted with the -r option, and may be re-enabled with the addition of the -e option. read [-run] name ... The first variable name may be of the form name?prompt. readonly [name ...] return [status] set [<i>_[a-z]] [<i>_</i+o keyword] ... Set (-) or clear a shell option: -a allexport all new variable are created with export attribute -e errexit exit on non-zero status [incorrect] bgnice background jobs are run with lower priority emacs BRL emacs-like line edit- ing ignoreeof shell will not exit of EOF, must use exit Printed 9/14/93 January 1988 6 KSH(1) USER COMMANDS KSH(1) -k keyword variable assignments are recognized anywhere in command markdirs [not implemented] -m monitor job control enabled (default for interactive shell) -n noexec compile input but do not execute (ignored if interactive) -f noglob don't expand filenames -u nounset dollar expansion of unset variables is an error -v verbose echo shell commands on stdout when compiling -h trackall add command pathnames to hash table vi VI-like line editing -x xtrace echo simple commands while executing set [--] arg ... Set shell arguments. shift [number] test See the attached manual page. times trap [handler] [signal ...] typeset [<i>_</i+irtx] [name[=value] ...] If no arguments are given, lists all variables and their attributes. If options but no names are given, lists variables with specified attributes, and their values if unless ``+'' is used. If names are given, set the attributes of the named vari- ables. Variables may also be assigned a value. If used inside a function, the created variable are local to the function. The attributes are as follows. -iThe variable's value is stored as an integer. -xThe variable is exported to the enviroment. -rThe variable is read-only cannot be reassigned a value. -tTrace (not implemented). -fList functions instead of variable. ulimit [ -<OZ> ] [ n ] -c Impose a size limit of n blocks on the size of Printed 9/14/93 January 1988 7 KSH(1) USER COMMANDS KSH(1) core dumps. -d Impose a size limit of n blocks on the size of the data area. -f Impose a size limit of n blocks on files written by the shell and its child processes (files of any size may be read). -m Impose a soft limit of n blocks on the size of physical memory. -t Impose a time limit of n seconds to be used by each process. If no option is given, -f is assumed. If n is omitted, the current limit is printed. As far as ulimit is con- cerned, a ``block'' is 512 bytes. You may lower your own resource limit, but only a super-user (see su(1M)) can raise a limit. umask [value] unalias name ... The aliases for the given names are removed. unset [-f] name ... wait [process-id] whence [-v] name ... For each name, the type of command is listed. The -v flag causes function and alias values to be listed. Job Control Job control features are enabled by the -m or -o monitor flags. When job control is enabled, and the system supports job control, background commands and foreground commands that have been stopped (usually by a SIGTSTP signal gen- erated by typing ^Z) are placed into separate individual process groups. The following commands are used to manipu- late these process groups: jobs Display information about the controlled jobs. The job number is given preceeded by a percent sign, followed by a plus sign if it is the ``current job'', or by a minus sign if it is the ``previous job'', then the process group number for the job, then the command. kill [-signal] job ... Send a signal (TERM by default) to the named Printed 9/14/93 January 1988 8 KSH(1) USER COMMANDS KSH(1) job process group. fg [ job ] Resume the stopped foreground job in the foreground. If the process group n is not specified then the ``current job'' is resumed. bg [ job ] Resume the stopped foreground job in the background. If the process group n is not specified then the ``current job'' is resumed. The fg, bg, kill, and wait commands may refer to jobs with the following ``percent'' sequences. The percent sign is optional with the fg and bg commands. %+(%-) If there is a ``current job'' (``previous job''), then that job is selected. %n If the specified job number is one of the known jobs, then that job is selected. %string If the string matches the initial part of a job's command, then that job is selected. %?string As above, but the string may match any portion of the command. If the system does not support job control, monitor mode enables job reporting. The jobs and kill commands functions as above, and you will be informed when background jobs com- plete. Fg and bg are not availiable. Interactive Input Line Editing When the emacs option is set, interactive input line editing is enabled. This mode is slightly different from the emacs mode in ATT's KornShell. In this mode various editing com- mands (typically bound to one or more control characters) cause immediate actions without waiting for a new-line. Several editing commands are bound to particular control characters when the shell is invoked; these bindings can be changed using the following commands: bind The current bindings are listed. bind [ string ] = [ editing-command ] The specified editing command is bound to the given string, which should con- sist of a control character (which may be written using ``caret notation'' ^x), optionally preceded by one of the two prefix characters. Future input of the string will cause the editing command to be immediately invoked. Note that although only two prefix char- acters (normal ESC and ^X) are sup- ported, some multi-character sequences can be supported: Printed 9/14/93 January 1988 9 KSH(1) USER COMMANDS KSH(1) bind '^[['=prefix-2 bind '^XA'=up-history bind '^XB'=down-history bind '^XC'=forward-char bind '^XC'=backward-char will bind the arrow keys on an ANSI ter- minal. Of course some escape sequences won't work out quite that nicely. bind -m [ string ] = [ substitute ] The specified input string will after- wards be immediately replaced by the given substitute string, which may con- tain editing commands. The following editing commands are available; first the com- mand name is given followed by its default binding (if any) using caret notation (note that the ASCII ESC character is written as ^[), then the editing function performed is decribed. Note that editing command names are used only with the bind command. Furthermore, many editing commands are useful only on terminals with a visible cursor. The default bindings were chosen to resemble corresponding EMACS key bindings. The users tty characters (eg. erase) are bound to reasonable substitutes. abort ^G Useful as a response to a request for a search-history pattern in order to abort the search. auto-insert Simply causes the character to appear as literal input. (Most ordinary characters are bound to this.) backward-char ^B Moves the cursor backward one character. backward-word ^[b Moves the cursor backward to the beginning of a word. beginning-of-line ^A Moves the cursor to the beginning of the input line (after the prompt string). complete ^[^[ Automatically completes as much as is unique of the hashed command name or the file name containing the cursor. If the entire remaining command or file name is unique a space is printed after its comple- tion, unless it is a direc- tory name in which case / is postpended. If there is no hashed command or file name Printed 9/14/93 January 1988 10 KSH(1) USER COMMANDS KSH(1) with the current partial word as its prefix, a bell character is output (usually causing a ``beep''). complete-command ^X^[ Automatically completes as much as is unique of the hashed command name having the partial word up to the cursor as its prefix, as in the complete command described above. Only com- mand and function names seen since the last hash -r com- mand are available for com- pletion; the hash command may be used to register additional names. complete-file ^[^X Automatically completes as much as is unique of the file name having the partial word up to the cursor as its prefix, as in the complete command described above. copy-last-arg ^[_ The last word of the previ- ous command is inserted at the cursor. Note I/O redirections do not count as words of the command. delete-char-backward ERASE Deletes the character before the cursor. delete-char-forward Deletes the character after the cursor. delete-word-backward ^[ERASE Deletes characters before the cursor back to the beginning of a word. delete-word-forward ^[d Deletes characters after the cursor up to the end of a word. down-history ^N Scrolls the history buffer forward one line (later). Each input line originally starts just after the last entry in the history buffer, so down-history is not use- ful until either search- history or up-history has been performed. end-of-line ^E Moves the cursor to the end of the input line. eot ^_ Acts as an end-of-file; this is useful because edit-mode input disables normal Printed 9/14/93 January 1988 11 KSH(1) USER COMMANDS KSH(1) terminal input canonicaliza- tion. eot-or-delete ^D Acts as eot if alone on a line; otherwise acts as delete-char-forward. exchange-point-and-mark ^X^X Places the cursor where the mark is, and sets the mark to where the cursor was. forward-char ^F Moves the cursor forward one position. forward-word ^[f Moves the cursor forward to the end of a word. kill-line KILL Deletes the entire input line. kill-to-eol ^K Deletes the input from the cursor to the end of the line. kill-region ^W Deletes the input between the cursor and the mark. list ^[? Prints a sorted, columnated list of hashed command names or file names (if any) that can complete the partial word containing the cursor. Directory names have / post- pended to them, and execut- able file names are followed by *. list-command ^X? Prints a sorted, columnated list of hashed command names (if any) that can complete the partial word containing the cursor. list-file Prints a sorted, columnated list of file names (if any) that can complete the par- tial word containing the cursor. File type indica- tors are postpended as described under list above. newline ^J and ^M Causes the current input line to be processed by the shell. (The current cursor position may be anywhere on the line.) newline-and-next ^O Causes the current input line to be processed by the shell, and the next line from history becomes the current line. This is only useful after an up-history or search-history. Printed 9/14/93 January 1988 12 KSH(1) USER COMMANDS KSH(1) no-op QUIT Does nothing. prefix-1 ^[ Introduces a 2-character command sequence. prefix-2 ^X Introduces a 2-character command sequence. quote ^^ The following character is taken literally rather than as an editing command. redraw ^L Reprints the prompt string and the current input line. search-character ^] Search forward in the current line for the next keyboard character. search-history ^R Enter incremental search mode. The internal history list is searched backwards for commands matching the input. An initial ``^'' in the search string anchors the search. The escape key will leave search mode. Other commands will be exe- cuted after leaving search mode (unless of course they are prefixed by escape, in which case they will almost certainly do the wrong thing). Successive search- history commands continue searching backward to the next previous occurrence of the pattern. The history buffer retains only a finite number of lines; the oldest are discarded as necessary. set-mark-command ^]<space> Search forward in the current line for the next keyboard character. stuff On systems supporting it, pushes the bound character back onto the terminal input where it may receive special processing by the terminal handler. stuff-reset Acts like stuff, then aborts input the same as an inter- rupt. transpose-chars ^T Exchanges the two characters on either side of the cur- sor, or the two previous characters if the cursor is at end of line. Printed 9/14/93 January 1988 13 KSH(1) USER COMMANDS KSH(1) up-history ^P Scrolls the history buffer backward one line (earlier). yank ^Y Inserts the most recently killed text string at the current cursor position. yank-pop ^[y Immediately after a yank, replaces the inserted text string with the next previ- ous killed text string.

FILES ~/.profile /etc/profile

SEE ALSO Sh(1) on System V or Sun OS. UNIX Shell Programming, Stephan G. Kochan, Patrick H. Wood, Hayden. KornShell: Command and Programming Language (not yet pub- lished), Morris Bolsky and David Korn.

AUTHORS Based on the public domain 7th edition Bourne shell. System V and Korn modifications by Eric Gisin, with contri- butions by Ron Natalie, Arnold Robbins, Doug Gwyn, Erik Baalbergen, ATT (getopt(3)). DIFFERENCES FROM ATT VERSION Vi editing mode is not implemented. The select statement is not implemented. Variable arrays are not implemented. Variable attributes other than integer are not implemented. The ERR and EXIT traps are not implemented for functions. Alias expansion is inhibited at the beginning of an alias definition in the ATT version. Korn evaluates expressions differently [elaborate].

BUGS Interactive shells will occasionally hang while waiting for a job in the BSD version. The 8th bit is stripped in emacs mode. Quoting double-quote (") characters inside back-quote (`) inside double-quotes does not behave properly. Why are you doing this? Job control on System V is not really job control. In fact it is not much of anything. Printed 9/14/93 January 1988 14 KSH(1) USER COMMANDS KSH(1) The emacs mode can ``lose'' stty command done by the user. Unsetting special variables may cause unexpected results. Functions declared as having local scope really have global scope. Here documents inside functions do not work correctly. Exit on error (set -e or set -o errexit) does not work correctly. Korn shell January 1988 15 TEST(1) USER COMMANDS TEST(1)

NAME test - test condition (Korn and 8th edition)

SYNOPSIS test expression [ expression ]

DESCRIPTION Test evalutates the expression and returns zero status if true, and non-zero status otherwise. It is normally used as the controlling command of the if and while statements. The following basic expressions are available. -r file file exists and is read- able -w file file exists and is writ- able -x file file exists and is exe- cutable -f file file is a regular file -d file file is a directory -c file file is a character spe- cial device -b file file is a block special device -p file file is a named pipe -u file file mode has setuid bit -g file file mode has setgid bit -k file file mode has sticky bit -s file file is not empty -L file file is a symbolic link -S file file is a socket file -nt file first file is newer than second file file -ot file first file is older than second file file -ef file first file is the same file as second file -t filedes file descriptor is a tty device string string is not null -z string string is null -n string string is not null string = string strings are equal string != string strings are not equal number -eq number numbers compare equal Korn shell January 1988 1 TEST(1) USER COMMANDS TEST(1) number -ne number numbers compare not equal number -ge number numbers compare greater than or equal number -gt number numbers compare greater than number -le number numbers compare less than or equal number -lt number numbers compare less than The above basic expressions may be combined with the follow- ing operators. expr -o expr logical or expr -a expr logical and ! expr logical not ( expr ) grouping

AUTHOR Erik Baalbergen. Modified by Arnold Robbins. Korn shell January 1988 2 GETOPTS(1) USER COMMANDS GETOPTS(1)

NAME getopts - parse command options

SYNOPSIS getopts optstring name [arg ...]

DESCRIPTION getopts is used by shell procedures to parse positional parameters and to check for legal options. It supports all applicable rules of the command syntax standard (see Rules 3-10, intro(1)). It should be used in place of the getopt(1) command. (See the WARNING, below.) optstring must contain the option letters the command using getopts will recognize; if a letter is followed by a colon, the option is expected to have an argument which should be separated from it by white space. Each time it is invoked, getopts will place the next option in the shell variable name and the index of the next argu- ment to be processed in the shell variable OPTIND. Whenever the shell or a shell procedure is invoked, OPTIND is ini- tialized to 1. When an option requires an option-argument, getopts places it in the shell variable OPTARG. If an illegal option is encountered, ? will be placed in name. When the end of the options is encountered, getopts exits with a non-zero exit status. The special option ``--'' may be used to delimit the end of the options. By default, getopts parses the positional parameters. If extra arguments (arg ...) are given on the getopts command line, getopts will parse them instead. So all new commands will adhere to the command syntax stan- dard described in intro(1), they should use getopts(1) or getopt(3C) to parse positional parameters and check for options that are legal for that command (see WARNINGS, below).

EXAMPLE The following fragment of a shell program shows how one might process the arguments for a command that can take the options a or b, as well as the option o, which requires an option-argument: while getopts abo: c do Korn shell January 1988 1 GETOPTS(1) USER COMMANDS GETOPTS(1) case $c in a|b) FLAGS=$FLAGS$c;; o) OARG=$OPTARG;; \?) echo $USAGE 1>&2 exit 2;; esac done shift OPTIND-1 This code will accept any of the following as equivalent: cmd -a -b -o "xxx z yy" file cmd -a -b -o "xxx z yy" -- file cmd -ab -o "xxx z yy" file cmd -ab -o "xxx z yy" -- file

SEE ALSO intro(1), sh(1). getopt(3C) in the Programmer's Reference Manual. UNIX System V Release 3.0 Release Notes.

WARNING Although the following command syntax rule (see intro(1)) relaxations are permitted under the current implementation, they should not be used because they may not be supported in future releases of the system. As in the EXAMPLE section above, a and b are options, and the option o requires an option-argument: cmd -aboxxx file (Rule 5 violation: options with option-arguments must not be grouped with other options) cmd -ab -oxxx file (Rule 6 violation: there must be white space after an option that takes an option-argument) Changing the value of the shell variable OPTIND or parsing different sets of arguments may lead to unexpected results.

DIAGNOSTICS getopts prints an error message on the standard error output when it encounters an option letter not included in opt- string. Korn shell January 1988 2


Retour