Museum

Home

Lab Overview

Retrotechnology Articles

Online Manuals

⇒ sh(1) — AIX PS/2 1.2.1

Media Vault

Software Library

Restoration Projects

Artifacts Sought

Related Articles

cd

echo

env, printenv

login

newgrp

pwd

test

umask

dup

exec

fork

statx

pipe

sigaction

ulimit

umask



SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



-------------------------------------------------------------------------------
sh, Rsh



PURPOSE

Interprets commands read from a file or entered at the keyboard.

SYNTAX


one of
+-----+   +--------+   +-----------------+  +------------------------------+
| sh  |---| +----+ |---| one of  one of  |--|           +--------------+   |--|
| Rsh |   +-| -i |-+   | +---+ 1 +-----+ |  | +- file --|              |-+ |
+-----+    ^| -r ||    +-| + |---| a n |-+  | |         +- parameters -+ | |
           |+----+|     ^| - |   | e t ||   +-|      one of              |-+
           +------+     |+---+   | f u ||     | +--------------+         |
                        |        | h v ||     +-| -c cmdstring |---------+
                        |        | k x ||       | -s           |
                        |        +-----+|       +--------------+
                        +---------------+


-----------------
1 Do not put a blank between these items.


DESCRIPTION

The sh command is a system command interpreter and programming language.  It is
not a part of the operating system kernel, but an ordinary user program that
reads commands entered at the keyboard and arranges for their execution.  In
addition, it can read commands that you have saved in a file.  Such a file is
usually called a shell procedure or a command file.  For a complete description
of how to write shell procedures to take advantage of this useful tool, see
Using the AIX Operating System.

A restricted version of shell (the Rsh command) is available that allows you to
create user environments with a limited set of privileges and capabilities.
See "Restricted Shell" for additional information on the restricted shell.

Commands

A command is either a simple command or control command (see "Control
Commands").

A simple command is a sequence of words separated by blanks.  A blank is a
space or a tab.  A word is a sequence of characters and/or numerals that
contains no blanks unless they occur within quote marks.  Japanese characters
must be separated by spaces if they are to be treated as separate words.  The



Processed November 8, 1990       SH, RSH(1,C)                                 1





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



first word in the sequence usually specifies the name of a command.  Any
remaining words, with a few exceptions, are passed to that command.  The
command name is passed as argument 0 (see the exec system call in the AIX
Operating System Technical Reference).

The value of a simple command is its exit value if it ends normally or (octal)
200 + status if it ends abnormally.  For a list of status values, see the
sigaction system call in AIX Operating System Technical Reference.

A pipeline is a sequence of one or more commands separated by a | (vertical
bar) or, for historical compatibility, by a ^ (circumflex).  In a pipeline, the
standard output of each command but the last becomes the standard input of the
next command.  Each command runs as a separate process, and the shell waits for
the last command in the pipeline to end.  A filter is a command that reads its
standard input, transforms it in some way, then writes it to its standard
output.  A pipeline normally consists of a series of filters.  Although the
processes in a pipeline (except the first process) can execute in parallel,
they are synchronized to the extent that each program needs to read the output
of its predecessor.

The exit value of a pipeline is the exit value of the last command.

A list is a sequence of one or more pipelines separated by ; (semicolon), "&"
(ampersand), "&&" (two ampersands), or || (two vertical bars) and optionally
ended by a ; (semicolon) or an "&" (ampersand).  These separators and
terminators have the following effects:

;     Causes sequential execution of the preceding pipeline (the shell waits
      for the pipeline to finish).

&     Causes asynchronous execution of the preceding pipeline (the shell does
      not wait for the pipeline to finish).

&&    Causes the list following it to be executed only if the preceding
      pipeline returns a zero exit value.

||    Causes the list following it to be executed only if the preceding
      pipeline returns a nonzero exit value.

      Note:  The cd command is an exception.  If it returns a nonzero exit
             value, no subsequent commands in a list are executed, regardless
             of the separator characters.

The ; and "&" separators have equal precedence, as do "&&" and ||.  The
single-character separators have lower precedence than the double-character
separators.  An unquoted new-line character following a pipeline functions the
same as a ; (semicolon).

Note:  The shell treats as a comment any word that begins with a # character
       and ignores that word and all characters following up to the next
       new-line character.




Processed November 8, 1990       SH, RSH(1,C)                                 2





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



Command Execution

Each time the shell executes a command, it carries out the substitutions
discussed in the following text.  Substitutions are performed in the order they
are described below.  If the command name matches one of the built-in commands
discussed in "Built-in Commands," it executes it in the shell process. If the
command name does not match a built-in command but matches the name of a
defined function, it executes the function in the shell process.  The shell
sets the positional parameters $1, $2, etc. to the parameters of the function.

If the command name matches neither a built-in command nor the name of a
defined function and the command names an executable file that is a compiled
(binary) program, the shell (as parent) spawns a new (child) process that
immediately runs the program.  If the file is marked executable but is not a
compiled program, the shell assumes that it is a shell procedure.  In this
case, the shell spawns another instance of itself (a subshell), to read the
file and execute the commands included in it (note how this differs from the
execution of functions).  The shell also executes a parenthesized command in a
subshell (see page         20).  From your point of view as a user, a compiled
program is run in exactly the same way as a shell procedure.

The shell parameter PATH defines the search path for the directory containing
the command.  Alternative directory names are separated by a colon (:).  The
default path is /bin:/usr/bin:/usr/ucb/:.  The current directory is specified
by a null path name, which can appear immediately after the equal sign or
between the colon delimiters anywhere else in the path list.  If the command
name contains a /, the search path is not used; such commands are not executed
by the restricted shell.  Otherwise, each directory in the path is searched for
an executable file.

You can change the particular sequence of directories searched by resetting the
PATH variable (page         9).

The shell remembers the location in the search path of each executed command
(to avoid unnecessary execs later).  If the command was found in a relative
directory (one whose name does not being with /), the shell must redetermine
its location whenever the current directory changes.  The shell forgets all
remembered locations whenever you change the PATH variable or execute the hash
-r command (page         22).

Signals

The shell ignores INTERRUPT and QUIT signals for an invoked command if the
command is terminated with a "&" (that is, if it is running in the background).
Otherwise signals have the values inherited by the shell from its parent, with
the exception of SIGSEGV (see also the built-in trap command on page
        24).

The .profile File

A shell acts as a "login shell" if it is invoked through the exec system call
and the first character of argument zero is - (minus sign).  Before a login



Processed November 8, 1990       SH, RSH(1,C)                                 3





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



shell reads your commands, it checks to see if a file named /etc/profile exists
on the system, and if it does, it reads commands from it (this file should set
variables needed by all users).  After this, the shell looks for a file named
.profile in your login directory.  If it finds one, it executes commands from
it.  Finally, the shell is ready to read commands from your standard input.

Command Substitution

To capture the output of any command as an argument to another command, place
that command line within grave accents (` `).  This concept is known as command
substitution.  The shell first executes the command or commands enclosed within
the grave accents, and then replaces the whole expression, grave accents and
all, with their output.  This feature is often used in assignment statements:

  today=`date`

This statement assigns the string representing the current date to the variable
"today".  The following assignment saves, in the variable "files", the number
of files in the current directory:

  files=`ls | wc -l`

You can enclose any command that writes to standard output in grave accents.
You can nest command substitutions as long as you quote the inside sets of
grave accents with a preceding \ (backslash):

  logmsg=`echo Your login directory is \`pwd\``

Substitutions

The character $ is used to introduce substitutable parameters.  There are two
types of parameters:  positional and keyword.  The shell has several mechanisms
for creating variables (assigning a string value to a name), as described in
the following sections.

Positional Parameters

When you run a shell procedure, the shell implicitly creates positional
parameters that reference each word on the command line by its position on the
command line.  The word in position "0" (the procedure name), is called "$0",
the next word (the first parameter) is called "$1", and so on up to "$9".  To
refer to command line parameters numbered higher than 9, use the built-in shift
command (page         24).

You can also assign values to these positional parameters explicitly by using
the built-in set command (page         23), or with shell functions.









Processed November 8, 1990       SH, RSH(1,C)                                 4





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



Notes:

  1. When an argument for a position is not specified, its positional parameter
    is set to null.

  2. Positional parameters are global and are reset by calling nested shell
    functions.  They are not restored when the function returns.

Keyword Parameters

The shell also recognizes alphanumeric variables to which string values can be
assigned.  You assign a string value to a name, as follows:

name"="string

A name is a sequence of letters, digits, and underscores that begins with a
letter or underscore.  To use the value that you have assigned to a variable,
add a "$" (dollar sign) to the beginning of its name.  Thus, "$"name yields the
value string.  No blanks surround the = (equal sign) in an assignment
statement.  (Positional parameters cannot appear in a assignment statement;
they can only be set as described earlier.)  You can put more than one
assignment on a command line.  The shell performs the assignments from right to
left.  If you have selected a language (through the LANG environment variable)
that supports multibyte characters, name and string can contain multibyte
characters; the = (equal sign) must be in ASCII.

If you surround string with quotation marks, either double or single (" "
' '), the shell does not treat spaces, tabs, semicolons, and new-line
characters within it as word delimiters but imbeds them literally in the
string.

If you surround string with double quotation marks (" "), the shell still
recognizes variable names in the string and performs parameter substitution;
that is, it replaces references to positional parameters and other variable
names that are prefaced by "$" with their corresponding values, if any.  The
shell also performs command substitution (see "Command Substitution") within
strings that are surrounded by double quotation marks.

If you surround string with single quotation marks (' '), the shell does no
variable or command substitution within the string.  The following sequence
illustrates this difference:

     You: stars=*****
          asterisks1="Add $stars"
          asterisks2='Add $stars'
          echo $asterisks1

  System: Add *****

     You: echo $asterisks2

  System: Add $stars



Processed November 8, 1990       SH, RSH(1,C)                                 5





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)




The shell does not reinterpret blanks in assignments after parameter
substitution (see "Blank Interpretation").  Thus the following assignments
result in "$first" and "$second" having the same value:

  first='a string with embedded blanks'
  second=$first

When you reference a parameter, you can enclose the parameter name (or the
digit designating a positional parameter) in "{ }" (braces) to delimit the
parameter name from any following string.  In particular, if the character
immediately following the name is a letter, digit, or underscore and the
parameter is not a positional parameter, the braces are required:

     You: a='This is a'
          echo "${a}n example"

  Display: This is an example

     You: echo "$a test"

  Display: This is a test

See "Conditional Substitution" for a different use of braces in parameter
substitutions.

Conditional Substitution

Normally, the shell replaces "$"name with the string value assigned to name, if
there is one.  However, there is a special notation that allows conditional
substitution, depending on whether the variable is set and/or not null.  By
definition, a variable is set if it has ever been assigned a value.  The value
of a variable can be the null string, which you can assign to a variable in any
one of the following ways:

  A=
  bcd=""
  Efg=''
  set '' ""

The first three of these examples assign the null string to each of the
corresponding variable names.  The last example sets the first and second
positional parameters to the null string and unsets all other positional
parameters.

The following is a list of the available expressions you can use to perform
conditional substitution.  The parameter and string variables can contain
multibyte characters.







Processed November 8, 1990       SH, RSH(1,C)                                 6





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



"${"parameter-string"}"
               If the parameter is set, substitute the value of parameter in
               place of this expression.  Otherwise, replace this expression
               with the value of string.

"${"parameter:-string"}"
               If the parameter is set and is not null, substitute the value of
               parameter in place of this expression.  Otherwise, replace this
               expression with the value of string.

"${"parameter=string"}"
               If the parameter is set, substitute the value of parameter in
               place of this expression.  Otherwise, set parameter to string
               and then substitute the value of the parameter in place of this
               expression.  You cannot assign values to positional parameters
               in this fashion.

"${"parameter:=string"}"
               If the parameter is set and is not null, substitute the value of
               parameter in place of this expression.  Otherwise, set parameter
               to string and then substitute the value of the parameter in
               place of this expression.  You cannot assign values to
               positional parameters in this fashion.

"${"parameter?string"}"
               If the parameter is set, substitute the value of parameter in
               place of this expression.  Otherwise, display a message of the
               form:

               parameter:    string

               and act as if the current simple command failed with a status of
               -1.  If you do not specify string, the shell displays the
               following message:

               parameter:     "parameter null or not set"

"${"parameter:?string"}"
               If the parameter is set and not null, substitute the value of
               parameter in place of this expression.  Otherwise, display a
               message of the form:

               parameter:    string

               and act as if the current simple command failed with a status of
               -1.  If you do not specify string, the shell displays the
               following message:

               parameter:     "parameter null or not set"






Processed November 8, 1990       SH, RSH(1,C)                                 7





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



"${"parameter+string"} "
               If the parameter is set, substitute the value of string in place
               of this expression.  Otherwise, substitute the null string.

"${"parameter:+string"} "
               If the parameter is set and not null, substitute the value of
               string in place of this expression.  Otherwise, substitute the
               null string.

In conditional substitution, the shell does not evaluate string until it uses
it as a substituted string, so that, in the following example, the shell
executes the pwd command only if d is not set or is null:

  echo ${d:-`pwd`}

Parameters Used by the Shell

The shell uses the following parameters.  The shell sets some of them and you
can set or reset all of them.  This set of parameter names must contain only
ASCII characters.  The values that correspond to the parameters can contain
multibyte characters.

CDPATH              The search path for the cd (change directory) command (see
                    the PATH variable in the following list for an explanation
                    of search paths).

HOME                The name of your login directory, the directory that
                    becomes the current directory upon completion of a login.
                    The login program initializes this variable.  The cd
                    command uses the value of $HOME as its default value.  If
                    you use this variable in your shell procedures rather than
                    using explicit full path name, your procedures run even if
                    your login directory is changed or if another user runs
                    them.

LANG                If used to initialize the shell's international
                    environment, specifies a valid locale name.  LANG
                    identifies general requirements for language, cultural
                    data, and character code set.

LC_COLLATE          Identifies requirements for text collation.

LC_CTYPE            Identifies requirements for character classification and
                    case conversion.

LC_MESSAGE          Determines the language in which the system error messages
                    appear.

LC_MONETARY         Specifies requirements for formatting monetary values.

LC_NUMERIC          Identifies requirements for number formats.




Processed November 8, 1990       SH, RSH(1,C)                                 8





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



LC_TIME             Specifies the locale's requirements for data and time
                    formats.

MAIL                The path name of the file used by the mail system to detect
                    the arrival of new mail.  If MAIL is set, the shell
                    periodically checks the modification time of this file and
                    displays the value of $MAILMSG if this time changes and the
                    length of the file is greater than zero.

                    You should set MAIL in your .profile file.  The value
                    normally assigned to it by users of the mail command is
                    $HOME/.newmail.

MAILCHECK           The number of seconds that the shell lets elapse before
                    checking again for the arrival of mail in the files
                    specified by the MAILPATH or MAIL parameters.  The default
                    value is 600 seconds (10 minutes).  If you set MAILCHECK to
                    0, the shell checks before each prompt.

MAILPATH            A colon-separated list of file names (see PATH).  If you
                    set this parameter, the shell informs you of the arrival of
                    mail in any of the files specified in the list.  You can
                    follow each file name by a "%" (percent sign) and a message
                    to be displayed when mail arrives.  Otherwise, the shell
                    uses the value of MAILMSG or by default ""you have mail"".

                    Note:  When MAILPATH is set, these files are checked
                           instead of the file set by MAIL.  To check the files
                           set by MAILPATH and the file set by MAIL, specify
                           the MAIL file in your list of MAILPATH files.

MAILMSG             The mail notification message.  If you explicitly set
                    MAILMSG to a null string ("MAIL="""), no message is
                    displayed.

PATH                An ordered list of directory path names separated by
                    colons.  The shell searches these directories in the
                    specified order when it looks for commands.  A null string
                    anywhere in the list represents the current directory.

                    PATH is normally initialized in the /etc/profile file,
                    usually to /bin:/usr/bin:/usr/ucb:.  You can reset this
                    variable to suit your own needs.  Thus if you wish to
                    search your current directory first, rather than last, you
                    would enter:

                      PATH=:/bin:/usr/bin:/usr/ucb

                    where, by definition, a null string is assumed in front of
                    the leading colon.  If you have a personal directory of
                    commands (say, $HOME/bin) that you want searched before the
                    standard system directories, set your PATH as follows:



Processed November 8, 1990       SH, RSH(1,C)                                 9





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)




                      PATH=$HOME/bin:/bin:/usr/bin:/etc::

                    The best place to set your PATH to something other than the
                    default value is in your .profile file (see "The .profile
                    File").  You cannot reset PATH if you are executing
                    commands under the restricted shell.

PS1                 The string to be used as the primary system prompt.  An
                    interactive shell displays this prompt string when it
                    expects input.  The default value of PS1 is ""$"" (a "$"
                    followed by a space).

PS2                 The value of the secondary prompt string.  If the shell
                    expects more input when it encounters a new-line character
                    in its input, it prompts with the value of PS2.  The
                    default value of PS2 is "> " (a > followed by a blank
                    space).

IFS                 The characters that are internal field separators (the
                    characters that the shell uses during blank interpretation,
                    see "Blank Interpretation").  The shell initially sets IFS
                    to include the space, tab, and new-line characters.

SHACCT              The name of a file that you own.  If this parameter is set,
                    the shell writes an accounting record in the file for each
                    shell script executed.  You can use accounting programs
                    such as acctcom and acctcms to analyze the data collected.

SHELL               A path name whose simple part (the part after the last /)
                    contains an "r" if you want the shell to become restricted
                    when invoked.  This should be set and exported by the
                    "$"HOME/.profile file of each restricted login.

TIMEOUT             A number of minutes.  After the shell displays its prompt,
                    you have TIMEOUT minutes to enter a command.  If you fail
                    to do so, the shell exits; in the login shell, such an exit
                    is a logout.  Setting TIMEOUT to 0 inhibits automatic
                    logout.

Predefined Special Parameters

Several variables have special meanings; the following are set only by the
shell:

$#    The number of positional parameters passed to the shell or most recently
      called function, not counting the name of the shell procedure or function
      itself.  "$#" thus yields the number of the highest-numbered positional
      parameter that is set.  One of the primary uses of this variable is to
      check for the presence of the required number of arguments.





Processed November 8, 1990       SH, RSH(1,C)                                10





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



$?    The exit value of the last command executed.  Its value is a decimal
      string.  Most AIX commands return 0 to indicate successful completion.
      The shell itself returns the current value of "$?" as its exit value.

$$    The process number of the current process.  Because process numbers are
      unique among all existing processes, this string of up to seven digits is
      often used to generate unique names for temporary files.  The following
      example illustrates the recommended practice of creating temporary files
      in a directory used only for that purpose:

        temp=$HOME/temp/$$
        ls >$temp
           .
           .
           .
        rm $temp

$*    All positional parameters to this shell starting with $1.

$@    Same as $* except that $@ is treated specially inside double quotation
      marks (see "Quoting Mechanisms").

$!    The process number of the last process run in the background (using the
      "&" terminator).  Again, this is a string of up to seven digits.

$-    A string consisting of the names of the execution flags (page         23)
      currently set in the shell.

Blank Interpretation

After the shell performs parameter and command substitution, it scans the
results for internal field separators (those defined in the shell variable IFS,
see page         10).  It splits the line into distinct words at each place it
finds one of these characters.  It retains explicit null arguments ("""  ''")
and discards implicit null arguments (those resulting from parameters that have
no values).

File-name Substitution

Command parameters are very often file names.  You can automatically produce a
list of file names as parameters on a command line by specifying a pattern that
the shell matches against the file names in a directory.

Most characters in such a pattern match themselves, but you can also use some
special pattern-matching characters in your pattern.  These special characters
are:

*                   Matches any string, including the null string.

?                   Matches any one character.





Processed November 8, 1990       SH, RSH(1,C)                                11





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



[...]               Matches any one of the characters enclosed in square
                    brackets.

[!...]              Matches any character other than one of the characters that
                    follow the exclamation mark within square brackets.

Inside square brackets, a pair of characters separated by a - (minus) specifies
a set of all characters lexically within the inclusive range of that pair,
according to the current collating sequence (see "ctab").  The LANG or
LC_COLLATE environment variable controls the collating sequence.

The current collating sequence may group characters into equivalence classes
for the purpose of defining the end points of a range of characters.  For
example, if the collating sequence defines the lexical order to be "AaBbCc..."
and groups uppercase and lowercase characters into equivalence classes, then
all the following have the same effect:  "[a-c]", "[A-C]", "[a-C]", and
"[A-c]".

Pattern matching has some restrictions.  If the first character of a file name
is a . (dot), it can be matched only by a pattern that literally begins with a
dot.  For example, "*" matches the file names "myfile" and "yourfile" but not
the file names ".myfile" and ".yourfile".  To match these files, use a pattern
such as the following:

  .*file

The character @ at the end of the pattern or immediately preceding a \ is
ignored during the matching.  However, the @ is appended to the corresponding
component of the matched file names to allow hidden directories to be
referenced directly (see Overview of the Technical Reference, Hidden
Directories section).

When the onsite control command is used, the <LOCAL> alias name for the
specified site is used for file name generation.  Otherwise, the invoking
shell's current <LOCAL> alias name is used (see the getlocal system call in the
AIX Operating System Technical Reference).

If a pattern does not match any file names, the pattern itself is returned as
the result of the attempted match.

File and directory names should not contain the characters "*", "?", [, or ]
because this can cause confusion.

Quoting Mechanisms

The following characters have special meaning to the shell and cause
termination of a word unless quoted.








Processed November 8, 1990       SH, RSH(1,C)                                12





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



       ;   semicolon                 <     less than
       &   ampersand                 >     greater than
     ( )   parenthesis                     newline
       |   vertical bar                    space
                                           tab

Sometimes you want to conceal this special meaning.  Single (' ') and double
(" ") quotation marks surrounding a string or a backslash (\) before a single
character provide this function in somewhat different ways.

Within single quotation marks, all characters (except the single quotation
character itself), are taken literally, with any special meaning removed.
Thus:

  stuff='echo $? $*; ls * | wc'

results only in the literal string "echo $? $*; ls * | wc" being assigned to
the variable "stuff"; the "echo", "ls", and "wc" commands are not executed, nor
are the variables "$?" and "$*" and the special character "*" expanded by the
shell.

Within double quotation marks, the special meaning of certain characters (the
"$", "`", "\", and ") does persist, while all other characters are taken
literally.  Thus, within double quotation marks, command and variable
substitution takes place.  In addition, the quotation marks do not affect the
commands within a command substitution that is part of the quoted string, so
characters there retain their special meanings.  Even if the value of a
substituted parameter contains blanks, the string enclosed in double quotation
marks is treated as a single word.  An exception is that while "$*" is
equivalent to "$1 $2 $3", etc., "$@" is equivalent to "$1", "$2", etc.

Consider the following sequence:

     You: ls *

  Display: file1 file2 file3

     You: message="This directory contains `ls * ` "
          echo $message

  Display: This directory contains file1 file2 file3

This shows that the "*" special character inside the command substitution was
expanded.

To hide the special meaning of "$", `, and " within double quotation marks,
precede these characters with a \ (backslash).  Outside of double quotation
marks, preceding a character with \ is equivalent to placing it within single
quotation marks.  Hence, a \ immediately preceding the new-line character (that
is, a \ at the end of the line) hides the new-line character and allows you to
continue the command line on the next physical line.




Processed November 8, 1990       SH, RSH(1,C)                                13





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



A Command's Environment

The environment is a list of name-value pairs inherited from the parent
process.  On invocation, the shell scans the environment and creates a
parameter for each name found, giving it the corresponding value.

The shell passes to its child processes the variables that have been named as
arguments to the built-in export command.  export places the named variables in
the environments of both the shell and all its future child processes.  All
parameters picked up from the shell's environment at start-up are included in
the export list.

The environment for any simple command may be augmented by prefixing it with
one or more assignments to parameters.  If the -k flag is set, all such
assignments are placed in the environment, even if they occur after the command
name.

For example, given the following simple procedure that echoes the values of two
variables (saved in a command file named "key_command"):

  #          key_command
  echo $a $b

the following command lines produce the output shown:

     You: a=key1 b=key2 key_command

  Display: key1 key2

     You: a=tom b=john key_command
  Display: tom john

Parameters passed through the environment are not included in the parameter
count stored in "$#".

A procedure can access the values of any variables in its environment; however,
if it changes any of the parameters associated with these environment
variables, these changes are not reflected in the shell environment.  They are
local to the procedure in question.  To place these changes in the environment
that the procedure passes to its child processes, you must export these values
within that procedure (but see also the -a on page         23).

A parameter can be removed from the environment with the built-in unset
command.

To obtain a list of variables that have been made exportable from the current
shell, enter:

  export

To get a list of name-value pairs in the current environment, enter:




Processed November 8, 1990       SH, RSH(1,C)                                14





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



  env

Redirection of Input and Output

In general, most commands do not know or care whether their input or output is
associated with the keyboard, the display screen, or a file.  Thus a command
can be used conveniently either at the keyboard or in a pipeline.

Standard Input and Standard Output

When a command begins running, it usually expects that three files are already
open: standard input, standard output, and diagnostic output (sometimes called
error output or standard error output).  A number called a file descriptor is
associated with each of these files as follows:

File descriptor 0     Standard input

File descriptor 1     Standard output

File descriptor 2     Diagnostic (error) output

A child process normally inherits these files from its parent; all three files
are initially assigned to the work station (0 to the keyboard, 1 and 2 to the
display).  The shell permits them to be redirected elsewhere before control is
passed to a command.  Any argument to the shell in the form <file or >file
opens the specified file as the standard input or output, respectively.  In the
case of output, this process destroys the previous contents of file, if it
already exists.  An argument in the form >>file directs the standard output to
the end of file, thus allowing you to append data.  If file does not exist, the
shell creates it.

Such redirection arguments are subject only to variable and command
substitution; neither blank interpretation nor pattern matching of file names
occurs after these substitutions.  Thus:

  echo 'this is a test' > *.ggg

produces a one-line file named "*.ggg" (a disastrous name for a file), and:

  cat < ?

produces an error message, unless you have a file named "?" (also a bad choice
for a file name).  If <> is used in place of >, the standard input is opened
with both read and write enabled.  The file must already exist as with <.

Diagnostic and Other Output

Diagnostic output from UNIX commands is normally directed to the file
associated with file descriptor 2.  You can redirect this error output to a
file by immediately preceding either output redirection arrow (> >>) with a "2"
(the number of the file descriptor).  For example, the following line appends
error messages from the cc command to the file "ERRORS":



Processed November 8, 1990       SH, RSH(1,C)                                15





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)




  cc testfile.c 2>> ERRORS

There must be no blanks between the file descriptor and the redirection symbol;
otherwise, the shell interprets the number as a separate argument to the
command.

You can also use this method to redirect the input or output associated with
any of the first 10 file descriptors (numbered 0 through 9).  Any redirection
symbol (<, <<, >, >>, <>, or >&digit) may be preceded by a single digit to
override the default use of standard input or output.  For instance, if a
command ("cmd") writes to file descriptor 9 (although this is not a recommended
programming habit), you can capture that output in a file "savedata" as
follows:

  cmd 9> savedata

If a command writes to more than one output, you can independently redirect
each one.  Suppose that a command directs its standard output to file
descriptor 1, directs its error output to file descriptor 2, and builds a data
file on file descriptor 9.  The following command line redirects each of these
outputs to a different file:

  cmd > standard 2> error 9> data

Inline Input Documents

Upon seeing a command line of the form:

"cmd <<" eofstring

where eofstring is any string that does not contain any pattern-matching
characters, the shell takes the subsequent lines as the standard input of "cmd"
until it reads a line consisting of only eofstring.  The lines between the
first eofstring and the second are frequently referred to as a here document.
If a - (minus) immediately follows the "<<", the shell strips leading tab
characters from each line of the input document before it passes the line to
the command.

The shell creates a temporary file containing the input document and performs
variable and command substitution on its contents before passing it to the
command.  It performs pattern matching on file names that are a part of command
lines in command substitutions.  If you want to prohibit all substitutions,
quote any character of eofstring:

"cmd << "\eofstring

The here document is especially useful for a small amount of input data that is
more conveniently placed in the shell procedure rather than kept in a separate
file (such as editor "scripts").  For instance, you could enter:





Processed November 8, 1990       SH, RSH(1,C)                                16





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



  cat <<- xyz
                                            This message is shown on the
                                            display with leading tabs removed.
  xyz

This feature is most useful in shell procedures.  Inline input documents cannot
appear within grave accents (command substitution).

A << may also be preceded by a digit to use an input file descriptor other than
1.

Input and Output Redirection Using File Descriptors

As discussed previously, a command occasionally directs output to some file
associated with a file descriptor other than "1" or "2".  The shell also
provides a mechanism for creating an output file associated with a particular
file descriptor.  By entering:

fd1">&"fd2

where fd1 and fd2 are valid file descriptors, you can direct the output that
would normally be associated with file descriptor fd1 to the file associated
with fd2.  The default value for fd1 and fd2 is "1" (standard output).  If, at
execution time, no file is associated with fd2, the redirection is void.  The
most common use of this mechanism is to direct standard error output to the
same file as standard output, as follows:

  cmd 2>&1

If you want to redirect both standard output and standard error output to the
same file, enter:

  cmd > file  2>&1

The order here is significant.  First, the shell associates file descriptor "1"
with "file"; then it associates file descriptor "2" with the file that is
currently associated with file descriptor "1".  If you reverse the order of the
redirections, standard error output goes to the display and standard output
goes to "file" because at the time of the error output redirection, file
descriptor "1" is still associated with the display.

You can also use this mechanism to redirect standard input.  You could enter:

fda"<&"fdb

to cause both file descriptors to be associated with the same input file.  For
commands that run sequentially, the default value of fda and fdb is "0"
(standard input).  For commands that run asynchronously (commands terminated by
"&"), the default value of fda and fdb is /dev/null.  Such input redirection is
useful for commands that use two or more input sources.





Processed November 8, 1990       SH, RSH(1,C)                                17





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



Summary of Redirection Options

The following can appear anywhere in a simple command or can precede or follow
a command, but they are not passed to the command:

<file  Use file as standard input.

>file  Use file as standard output.  Create the file if it does not exist;
       otherwise truncate it to zero length.

<>     Same as >file, but open for read-write and default to standard input.

>>file Use file as standard output.  Create the file if it does not exist;
       otherwise add the output to the end of the file.

<<[-]eofstr
       Read as standard input all lines from eofstr up to a line containing
       only eofstr or up to an end-of-file character.  If any character in
       eofstr is quoted, the shell does not expand or interpret any characters
       in the input lines; otherwise, it performs variable and command
       substitution and ignores a quoted new-line character (\new-line).  Use a
       \ to quote characters within eofstr or within the input lines.

       If you add a - (minus) to << then all leading tabs are stripped from
       eofstr and from the input lines.

<"&"digit
       Associate standard input with file descriptor digit.  (generalizes to
       fd1"<&"fd2 as does <"&"digit).

>"&"digit
       Associate standard output with file descriptor digit.

<"&"-  Close standard input.

>"&"-  Close standard output.

Any of the above can be preceded by a digit to specify a file descriptor to use
instead of standard input or output.  The restricted shell does not allow the
redirection of output.

In each of the above, any open of a file uses the shell's current <LOCAL>
alias, even when the on control command is used.  If the file word contains
backquote command substitution, this expansion is performed on the local site
even if the on command is used.

Control Commands

The following are reserved words which are only recognized as special as the
first word of a command and when not quoted:

  if then else elif fi case esac for while until do done onsite {  }



Processed November 8, 1990       SH, RSH(1,C)                                18





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)




The shell provides several flow control commands that are useful in creating
shell procedures:

for name [ in word... ]


do list

done      For each word, sets name to word and executes the commands in list.
          If you omit in word . . ., the for command executes list for each
          positional parameter that is set.  Execution ends when there are no
          more words in the word list.

case word in


pattern [|pattern]...) list;;


[.

.
          .
          .



pattern [|pattern]...) list;;]


esac      Executes the commands in the list associated with the first pattern
          that matches word.  Uses the same character-matching notation in
          patterns that you use for file-name substitution (see "File-name
          Substitution"), except that you do not need to match explicitly a
          slash, a leading dot, or a dot immediately following a slash.  Also,
          reserved words cannot be used unless quoted.

if list

then list

[elif list ]...


[else list]


fi        Executes the list following the if keyword.  If it returns a zero
          exit value, execute the list following the first then.  Otherwise,
          execute the list following each elif (if there is an elif), and if
          its exit value is zero, execute the next then.  Failing that, execute



Processed November 8, 1990       SH, RSH(1,C)                                19





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



          the list following the else.  If no else list or then list is
          executed, the if command returns a zero exit value.

while list


do list

done      Executes the list following the while.  If the exit value of the list
          is zero, executes the list following do.  Continue looping through
          the lists until the exit value of the while list is nonzero.  If no
          commands in the do list are executed, the while command returns a
          zero exit value.

until list


do list

done      Executes the list following the until.  If the exit value of the list
          is nonzero, executes the list following do.  Continues looping
          through the lists until the exit value of the until list is zero.  If
          no commands in the do list are executed, the until command returns a
          zero exit value.

onsite [-v] sitename|sitenumber|sitetype command
          The command is run on the specified site, or on a site of the
          specified sitetype.  The command can be either a simple command or a
          control command as described on page         18.  If a sitename or
          sitenumber are given, the command is run on the specified site if it
          is accessible in the current partition.  The command is run using the
          <LOCAL> alias for the specified site (see getlocal in the AIX
          Technical Reference Vol II).  The site may be specified either by
          name, number, or cpu type.  Command substitution may be used on the
          site argument to allow a program to chose the best (for example,
          least loaded) site on which to execute.  The <LOCAL> alias for the
          specified site is used in file name generation; but when opening
          files specified for input/output redirection, the invoking shell's
          current <LOCAL> alias and current site number are used for filename
          expansion.  Because the value of the <LOCAL> alias may effect the
          directories in the PATH, the internal hash table is not used during
          execution of this command (as if the hash -r command had been used).
          If the -v option is given, the shell tells the user which site is
          being used in the command.

(list)    Executes the commands in list in a subshell.

{ list; } Executes the commands in list in the current shell process (does not
          spawn a subshell).






Processed November 8, 1990       SH, RSH(1,C)                                20





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



name () {  list;  }
          Defines a function that is referenced by name.  The body of the
          function is the list of commands between the braces.

Built-in Commands

:            Does nothing.  This null command returns a zero exit value.

.  file      Reads and executes commands from file and returns.  Does not spawn
             a subshell.  The search path specified by PATH is used to find the
             directory containing file.

break [n]    Exits from the enclosing for, while, or until loop, if any.  If n
             is specified, breaks n levels.

continue [n] Resumes the next iteration of the enclosing for, while, or until
             loop.  If n is specified, resumes at the nth enclosing loop.

cd [dir]     Changes the current directory to dir.  The value of the shell
             variable HOME is the default dir.  The shell variable CDPATH
             defines the search path for the directory containing dir.
             Alternative directory names appear in a colon-separated list.  A
             null path name specifies the current directory (which is the
             default path).  This null path name can appear immediately after
             the equal sign in the assignment or between the colon delimiters
             anywhere else in the path list.  If dir begins with a slash, the
             shell does not use the search path.  Otherwise, the shell searches
             each directory in the path.  cd cannot be executed by the
             restricted shell.

echo [arg...]
             Writes arguments to standard output.  See "echo" for a discussion
             of its usage and parameters.

eval [arg...]
             Reads arguments as input to the shell and executes the resulting
             command(s).

exec [arg...]
             Executes the command specified by argument in place of this shell
             without creating a new process.  Input and output arguments can
             appear and, if no other arguments appear, cause the shell input or
             output to be modified (not a good idea with your login shell).

exit [n]     Causes a shell to exit with the exit value specified by n.  If you
             omit n, the exit value is that of the last command executed (an
             end of file also causes a shell to exit).

export [name...]
             Marks the specified names for automatic export to the environments
             of subsequently executed commands.  If you do not specify a names,




Processed November 8, 1990       SH, RSH(1,C)                                21





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



             export displays a list of all names that are exported in this
             shell.  You cannot export function names.

hash [-r] [name...]
             For each name, finds and remembers the location in the search path
             of the command specified by name.  The -r flag causes the shell to
             forget all locations.  If you do not specify the flag or any
             names, the shell displays information about the remembered
             commands.  In this information, hits is the number of times a
             command has been run by the shell process.  Cost is a measure of
             the work required to locate a command in the search path.  There
             are certain situations that require that the stored location of a
             command be recalculated (for example, the location of a relative
             path name when the current directory changes).  Commands for which
             that might be done are indicated by an asterisk next to the hits
             information.  Cost is incremented when the recalculation is done.

migrate [-site] [pid ...]
             A request is made for the specified processes to be migrated to
             the specified site.  Pid is the process ID of the process to be
             migrated.  If pid is negative, it is the process group ID of the
             group to be migrated (the site must be explicitly specified if the
             first pid argument is negative).  'Site' may be specified by
             either name, number or machine type (for example i370, i386).  In
             any case, a dash must precede the site name, number or type.  The
             migrate does not begin until the process(es) have a chance to run.
             In particular, if they are stopped, they do not begin migrating
             until they are continued.  If no site is specified, the default is
             to "pull" the process to the shell's site.  If no pids are
             specified, the shell migrates itself (and also calls setlocal(S)).
             The command "migrate -site $$" will use migrate the shell will
             call setlocal.  Whenever setlocal is called, the hash -r command
             is automatically executed in case any files in PATH depend on the
             <LOCAL> alias.

newgrp [arg...]
             Executes the newgrp command in the current shell process.  See
             "newgrp" for a discussion of command options.

pwd          Displays the current directory.  See "pwd" for a discussion of
             command options.

read [name...]
             Reads one line from standard input.  Assigns the first word in the
             line to the first name, the second word to the second name, and so
             on, with leftover words assigned to the last name.  This command
             returns a 0 unless it encounters an end of file.

readonly [name...]
             Marks the specified names readonly.  The values of these names
             cannot be reset.  If you do not specify any names, readonly
             displays a list of all readonly names.



Processed November 8, 1990       SH, RSH(1,C)                                22





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)




return [n]   Cause a function to exit with a return value of n.  If you do not
             specify n, the function returns the status of the last command
             executed in that function.  This command is valid only when
             executed within a shell function.

set [flag...[arg]...]


             -a  Marks for export all variables that are modified or changed.

             -e  Exits immediately if any invoked command (other than a
                 built-in command) exits with a nonzero exit value.  Without
                 this flag, the shell does not exit if any invoked command
                 returns a nonzero exit status.

                 Note:  The shell always exits if any built-in command returns
                        a nonzero exit status, even if the -e flag is set.

             -f  Disables file-name substitution.

             -h  Locates and remembers the commands called within functions as
                 the functions are defined (normally these commands are located
                 when the function is executed.  See the hash command on page
                         22).

             -k  Places all keyword parameters in the environment for a
                 command, not just those that precede the command name.

             -n  Reads commands but does not execute them.

             -t  Exits after reading and executing one command.

             -u  Treats an unset variable as an error when performing variable
                 substitution.

             -v  Displays shell input lines as they are read.

             -x  Displays commands and their arguments as they are executed.

             --  Does not change any of the flags.  This is useful in setting
                 "$1" to a string beginning with a - (minus).

                 Using a + (plus) rather than a - (minus) unsets flags.  You
                 can also specify these flags on the shell command line.  The
                 special variable "$-" contains the current set of flags.

                 Any arguments to set are positional parameters and are
                 assigned, in order, to "$1", "$2", and so on.  If you do not
                 specify flags or parameters, set displays the values of all
                 parameters.




Processed November 8, 1990       SH, RSH(1,C)                                23





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



setxvers [string]
             If string is provided, it sets the experimental version prefix to
             string.  If string is not provided, it removes any previous
             experimental version string.  The prefix is used when searching
             hidden directories for executable files.  A hidden directory
             component that has a name beginning with the prefix string is
             selected for execution in preference to a component that has a
             name that doesn't begin with the experimental version string.  The
             experimental version prefix is inherited by child processes.  See
             AIX Operating System Technical Reference for more information on
             hidden directories and searching for executable files.

setspath [ LOCAL | site | cpu ] ...
             Sets the site path.  Sites may be specified by name or by number.
             CPU types may be specified by the same names which are used in
             hidden directories.  If an argument is specified as LOCAL, a
             "nullsite" site path entry is created (see setspath in the AIX
             Operating System Technical Reference).  The arguments to this
             command are file name and command substituted.

             Use this command with caution.  A poorly formed site path can make
             it difficult to execute any commands.

shift [n]    Shifts command line arguments to the left; that is, reassign the
             value of the positional parameters by discarding the current of
             value of "$1" and assigning the value of "$2" to "$1", of "$3" to
             "$2", and so on.  If there are more than 9 command line arguments,
             the tenth is assigned to "$9" and any that remain are still
             unassigned (until after another shift).  If there are 9 or fewer
             arguments, a shift unsets the highest-numbered positional
             parameter.

             "$0" is never shifted.  The command shift n is a shorthand
             notation for n consecutive shifts.  The default value of n is 1.

test expr | [ expr ]
             Evaluates conditional expressions.  See "test" for a discussion of
             command options.

times        Displays the accumulated user and system times for processes run
             from the shell.

trap [arg] [n...]
             Runs the command specified by arg when the shell receives
             signal(s) n, where n is any signal other than 11.  (The shell
             scans parm once when the trap is set and once when the trap is
             taken.)  trap commands are executed in order of signal number.
             Any attempt to set a trap on a signal that was ignored on entry to
             the current shell is ineffective.

             If you do not specify an arg, all trap(s) n are reset to their
             current values.  If arg is the null string, this signal is ignored



Processed November 8, 1990       SH, RSH(1,C)                                24





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



             by the shell and by the commands it invokes.  If n is 0, arg is
             executed on exit from the shell.  If you specify no arg and no n,
             trap displays a list of commands associated with each signal
             number.

type [name...]
             For each name, indicates how the shell would interpret it as a
             command name.

ulimit [-b [m]] [-f] [n] [-s [m]]
             Sets or queries size limits.  The -b flag sets the break value to
             m.  This limits the size of data segment to m pages.  If you
             specify -b with no m, ulimit displays the current break value.
             The -f flag imposes a size limit of n blocks on files written by
             the child processes (files of any size can be read).  Without n,
             ulimit displays the current limit (this is the default action of
             ulimit).

             Notes:

               1. Since the shell rounds n down to the nearest cluster size, it
                 is best to make it a multiple of 8 (for example, specifying
                 values of 1 thru n all result in a size limit of 0).

               2. Any user can decrease this limit, but only a user operating
                 with superuser authority can increase the limit.

             The -s flag imposes a size limit of m pages on the stack.  If you
             specify -s with no m, ulimit displays the current stack size
             limit.

umask [nnn]  Sets the user file-creation mask to nnn (see the umask system
             call).  If you omit nnn, umask displays the current value of the
             mask.

unset [name...]
             For each name, removes the corresponding variable or function.
             The variables PATH, PS1, PS2, MAILCHECK and IFS cannot be unset.

wait [n]     Waits for the child process whose process number is n to end and
             reports its termination status.  If you do not specify n, the
             shell waits for all currently active child processes and the
             return value is 0.

Running the Shell

The sh command can be run either as a login shell or as a command.  Only the
login command can call sh as a login shell.  It does this by using a special
form of the sh command name:  "-sh".  When called with an initial - (minus),
the shell first reads and runs commands found in the system profile file and
your "$"HOME/.profile, if one exists.  It then accepts commands as described in
the following discussion of flags.  Once logged in and working under a login



Processed November 8, 1990       SH, RSH(1,C)                                25





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



shell, you can call sh with the command name "sh".  This command runs a
subshell, a second shell running as a child of the login shell.

Restricted Shell

The restricted shell, Rsh, is used to set up login names and environments whose
capabilities are more controlled than those of the standard shell.  The actions
of Rsh are identical to those of sh, except that the following are not allowed:

  o Changing directory (see "cd")
  o Setting the value of "$"PATH
  o Specifying path or command names containing "/"
  o Redirecting output (>, >> and <>).

The restrictions above are enforced after .profile is interpreted, meaning that
the restrictions can override settings originally set in .profile.

When a command to be run is found to be a shell procedure, Rsh starts sh to run
it.  Thus, it is possible to provide to the end-user shell procedures that have
access to the full power of the standard shell, while imposing a limited menu
of commands; this scheme assumes that the end-user does not have write and run
permissions in the same directory.

The net effect of these rules is that the writer of the .profile has complete
control over user actions, by performing setup actions and leaving the user in
an appropriate directory (probably not the login directory).

When called with the name -Rsh, Rsh reads the user's .profile (from
$HOME/.profile).  It acts as the standard sh while doing this, except that an
interrupt causes an immediate exit instead of a return to command level.

FLAGS

The following flags are interpreted by the shell only when you call it.  Unless
you specify either the -c or -s flag, the shell assumes that the next parameter
is a command file (shell procedure).  It passes anything else on the command
line to that command file (see "Positional Parameters").

-c cmdstring
            Runs commands read from cmdstring.  The shell does not read
            additional commands from standard input when you specify this flag.

-i          Makes the shell interactive, even if input and output are not from
            a work station.  In this case the shell ignores the TERMINATE
            signal (so that kill 0 does not stop an interactive shell) and
            traps an INTERRUPT (so that you can interrupt wait).  In all cases,
            the shell ignores the QUIT signal.  (See the sigaction system call
            in AIX Operating System Technical Reference and "kill" for more
            information about signals.)

-r          Creates a restricted shell (the same as running Rsh).




Processed November 8, 1990       SH, RSH(1,C)                                26





SH, RSH(1,C)                AIX Commands Reference                 SH, RSH(1,C)



-s          Reads commands from standard input.  Any remaining parameters
            specified are passed as positional parameters to the new shell.
            Shell output is written to standard error, except for the output of
            built-in commands (see "Built-in Commands").

The remaining flags and parameters are described in the built-in set command on
page         23.

FILES

/etc/environment
/etc/profile
$HOME/.profile
/tmp/sh*
/dev/null
/etc/site

RELATED INFORMATION

See the following commands:  "cd,"  "echo,"  "env, printenv," "login,"
"newgrp,"  "pwd," "test" and "umask."

See the dup, exec, fork, statx, pipe, sigaction, ulimit, and umask system calls
and the a.out, .profile, and environ files in AIX Operating System Technical
Reference.

See "Using the Shell with Processes" and "Advanced Shell Features" in Using the
AIX Operating System.

See "Introduction to International Character Support" in Managing the AIX
Operating System.  See also "Programming for an MBCS Environment" in AIX
Operating System Programming Tools and Interfaces.























Processed November 8, 1990       SH, RSH(1,C)                                27



Typewritten Software • bear@typewritten.org • Edmonds, WA 98026