MAN page from RedHat 5.X ash-0.2-12.i386.rpm


Section: User Commands (1)
Updated: March 7, 1991


ash - a shell 


ash[-efIijnsxz] [+efIijnsxz] [-ccommand] [arg] ... 


Copyright 1989 by Kenneth Almquist. 


Ashis a version ofshwith features similar to those of the System V shell.This manual page lists all the features ofashbut concentrates on the ones not in other shells.If the-coptions is given, then the shell executes the specified shell command.The-sflag cause the shell to read commands from the standard input (afterexecuting any command specified with the-coption.If neither the-sor-coptions are set, then the firstargis taken as the name of a file to read commands from.If this is impossible because there are no arguments followingthe options, thenashwill set the-sflag and will read commands from the standard input.

The shell sets the initial value of the positional parameters from theargsremaining after anyargused as the name of a file of commands is deleted.

The flags (other than-c)are set by preceding them with ``-'' and cleared by preceding themwith ``+''; see thesetbuiltin command for a list of flags.If no value is specified for the-iflag, the-sflag is set, and the standard input and output of the shellare connected to terminals, then the-iflag will be set.If no value is specified for the-jflag, then the-jflag will be set if the-iflag is set.

When the shell is invoked with the-coption, it is good practice to include the-iflag if the command was entered interactively by a user.For compatibility with the System V shell, the-ioption should come after the-coption.

If the first character of argument zero to the shell is ``-'',the shell is assumed to be a login shell, and the files/etc/profileand.profileare read if they exist.If the environment variable SHINIT is set on entry to the shell,the commands in SHINIT are normally parsed and executed. SHINIT isnot examined if the shell is a login shell, or if it the shell is running ashell procedure. (A shell is considered to be running a shellprocedure if neither the-snor the-coptions are set.)Alistis a sequence of zero or more commands separated by newlines,semicolons, or ampersands, and optionally terminated by one of thesethree characters. (This differs from the System V shell, whichrequires a list to contain at least one command in most cases.) Thecommands in a list are executed in the order they are written.If command is followed by an ampersand, the shell starts the commandand immediately proceed onto the next command; otherwise it waitsfor the command to terminate before proceeding to the next one.

``&&'' and ``||'' are binary operators.``&&'' executes the first command, and then executes the second commandiff the exit status of the first command is zero. ``||'' is similar,but executes the second command iff the exit status of the first commandis nonzero. ``&&'' and ``||'' both have the same priority.

The ``|'' operator is a binary operator which feeds the standard outputof the first command into the standard input of the second command.The exit status of the ``|'' operator is the exit status of the secondcommand. ``|'' has a higher priority than ``||'' or ``&&''.

Anifcommand looks like

if listthen    list
[ elif list then list ] ...
[ else list ]fi

Awhilecommand looks like

while listdo      listdone

The two lists are executed repeatedly while the exit status of the firstlist is zero. Theuntilcommand is similar, but has the worduntilin place ofwhile
 repeats until the exit status of the first listis zero.

Theforcommand looks like

for variable in      listdone

The words are expanded, and then the list is executed repeatedly withthe variable set to each word in turn.doanddonemay be replaced with``{'' and ``}''.

Thebreakandcontinuecommands look like

break [ num ]continue [ num ]

Breakterminates thenuminnermostfororwhileloops.Continuecontinues with the next iteration of thenum'thinnermost loop.These are implemented as builtin commands.

Thecasecommand looks like

case word inpattern) list ;;...esac

The pattern can actually be one or more patterns (seePatternsbelow), separated by ``|'' characters.

Commands may be grouped by writing either



{ list; }

The first of these executes the commands in a subshell.

A function definition looks like

name ( ) command

A function definition is an executable statement; when executed it installsa function namednameand returns an exit status of zero.The command is normally a list enclosed between ``{'' and ``}''.

Variables may be declared to be local to a function by using alocalcommand. This should appear as the first staement of a function,and looks like

local [ variable | - ] ...

Localis implemented as a builtin command.

When a variable is made local, it inherits the initial value andexported and readonly flags from the variable with the same name in thesurrounding scope, if there is one. Otherwise, the variable isinitially unset.Ashuses dynamic scoping, so that if you make the variablexlocal to functionf,which then calls functiong,references to the variablexmade insidegwill refer to the variablexdeclared insidef,not to the global variable namedx.

The only special parameter than can be made local is ``-''.Making ``-'' local any shell options that are changed via thesetcommand inside the function to be restored to their original valueswhen the function returns.

Thereturncommand looks like

return [ exitstatus ]

It terminates the currently executing function.Returnis implemented as a builtin command.A simple command is a sequence of words. The execution of a simplecommand proceeds as follows. First, the leading words of the form``name=value'' are stripped off and assigned to the environment ofthe command. Second, the words are expanded. Third, the firstremaining word is taken as the command name that command is located.Fourth, any redirections are performed. Fifth, the command isexecuted. We look at these operations in reverse order.

The execution of the command varies with the type of command.There are three types of commands: shell functions, builtin commands,and normal programs.

When a shell function is executed, all of the shell positional parameters(except $0, which remains unchanged) are set to the parameters to the shellfunction. The variables which are explicitly placed in the environmentof the command (by placing assignments to them before the function name)are made local to the function and are set to values given.Then the command given in the function definition is executed.The positional parameters are restored to their original values whenthe command completes.

Shell builtins are executed internally to the shell, without spawninga new process.

When a normal program is executed, the shell runs the program, passingthe parameters and the environment to the program. If the program isa shell procedure, the shell will interpret the program in a subshell.The shell will reinitialize itself in this case, so that the effectwill be as if a new shell had been invoked to handle the shell procedure,except that the location of commands located in the parent shell willbe remembered by the child. If the program is a file beginning with``#!'', the remainder of the first line specifies an interpreter forthe program. The shell (or the operating system, under Berkeley UNIX)will run the interpreter in this case. The arguments to the interpreterwill consist of any arguments given on the first line of the program,followed by the name of the program, followed by the arguments passedto the program.Input/output redirections can be intermixed with the words in a simplecommand and can be placed following any of the other commands. Whenredirection occurs, the shell saves the old values of the file descriptorsand restores them when the command completes. The ``<'', ``>'', and ``>>''redirections open a file for input, output, and appending, respectively.The ``<&digit'' and ``>&digit'' makes the input or output a duplicateof the file descriptor numbered by the digit. If a minus sign is usedin place of a digit, the standard input or standard output are closed.

The ``<< word'' redirectiontakes input from aheredocument.As the shell encounters ``<<'' redirections, it collects them. Thenext time it encounters an unescaped newline, it reads the documentsin turn. The word following the ``<<'' specifies the contents of theline that terminates the document. If none of the quoting methods('', "", or \) are used to enter the word, then the document is treatedlike a word inside double quotes: ``$'' and backquote are expandedand backslash can be used to escape these and to continue long lines.The word cannot contain any variable or command substitutions, andits length (after quoting) must be in the range of 1 to 79 characters.If ``<<-'' is used in place of ``<<'', then leading tabs are deletedfrom the lines of the document. (This is to allow you do indent shellprocedures containing here documents in a natural fashion.)

Any of the preceding redirection operators may be preceded by a singledigit specifying the file descriptor to be redirected. There cannotbe any white space between the digit and the redirection operator.When locating a command, the shell first looks to see if it has ashell function by that name. Then, if PATH does not contain anentry for "%builtin", it looks for a builtin command by that name.Finally, it searches each entry in PATH in turn for the command.

The value of the PATH variable should be a series of entries separatedby colons.Each entry consists of a directory name, or a directory name followedby a flag beginning with a percent sign.The current directory should be indicated by an empty directory name.

If no percent sign is present, then the entry causes the shell tosearch for the command in the specified directory. If the flag is``%builtin'' then the list of shell builtin commands is searched.If the flag is ``%func'' then the directory is searched for a file whichis read as input to the shell. This file should define a functionwhose name is the name of the command being searched for.

Command names containing a slash are simply executed without performingany of the above searches.The environment of a command is a set of name/value pairs. When theshell is invoked, it reads these names and values, sets the shellvariables with these names to the corresponding values, and marksthe variables as exported. Theexportcommand can be used to mark additional variables as exported.

The environment of a command is constructed by constructing name/valuepairs from all the exported shell variables, and then modifying thisset by the assignments which precede the command, if any.The process of evaluating words when a shell procedure is executed iscalledexpansion.Expansion consists of four steps: variable substitution, commandsubstitution, word splitting, and file name generation. If a wordis the expression following the wordcasein a case statement, the file namewhich follows a redirection symbol, or an assignment to the environmentof a command, then the word cannot be split into multiple words. Inthese cases, the last two steps of the expansion process are omitted.To be written.Ashaccepts two syntaxes for command substitution:



Either of these may be included in a word.During the command substitution process, the command (syntactly alist)will be executed and anything that the command writes to the standardoutput will be captured by the shell. The final newline (if any) ofthe output will be deleted; the rest of the output will be substitutedfor the command in the word.When the value of a variable or the output of a command is substituted,the resulting text is subject to word splitting, unless the dollar signintroducing the variable or backquotes containing the text were enclosedin double quotes. In addition, ``$@'' is subject to a special type ofsplitting, even in the presence of double quotes.

Ash uses two different splitting algorithms. The normal approach, whichis intended for splitting text separated by which space, is used if thefirst character of the shell variable IFS is a space. Otherwise an alternativeexperimental algorithm, which is useful for splitting (possibly empty)fields separated by a separator character, is used.

When performing splitting, the shell scans the replacement text lookingfor a character (when IFS does not begin with a space) or a sequence ofcharacters (when IFS does begin with a space), deletes the character orsequence of characters, and spits the word into two strings at thatpoint. When IFS begins with a space, the shell deletes either of thestrings if they are null. As a special case, if the word containingthe replacement text is the null string, the word is deleted.

The variable ``$@'' is special in two ways. First, splitting takesplace between the positional parameters, even if the text is enclosedin double quotes. Second, if the word containing the replacementtext is the null string and there are no positional parameters, thenthe word is deleted. The result of these rules is that "$@" isequivalent to "$1" "$2" ... "$n", where n is the number ofpositional parameters. (Note that this differs from the System V shell.The System V documentation claims that "$@" behaves this way; in facton the System V shell "$@" is equivalent to "" when there are nopositional paramteters.)Unless the-fflag is set, file name generation is performed after word splitting iscomplete. Each word is viewed as a series of patterns, separated byslashes. The process of expansion replaces the word with the names ofall existing files whose names can be formed by replacing each patternwith a string that matches the specified pattern. There are tworestrictions on this: first, a pattern cannot match a string containinga slash, and second, a pattern cannot match a string starting with aperiod unless the first character of the pattern is a period.

If a word fails to match any files and the-zflag is not set, then the word will be left unchanged (except that themeta-characters will be converted to normal characters). If the-zflag is set, then the word is only left unchanged if noneof the patterns contain a character that can match anything besidesitself. Otherwise the-zflag forces the word to be replaced with the names of the files that itmatches, even if there are zero names.Apatternconsists of normal characters, which match themselves, and meta-characters.The meta-characters are ``!'', ``*'', ``?'', and ``[''. These characters losethere special meanings if they are quoted. When command or variablesubstitution is performed and the dollar sign or back quotes are notdouble quoted, the value of the variable or the output of the commandis scanned for these characters and they are turned into meta-characters.

Two exclamation points at the beginning of a pattern function as a ``not''operator, causing the pattern to match any string that the remainder ofthe pattern doesnotmatch. Other occurances of exclamation points in a pattern matchexclamation points. Two exclamation points are required rather than oneto decrease the incompatibility with the System V shell (which does nottreat exclamation points specially).

An asterisk (``*'') matches any string of characters.A question mark matches any single character.A left bracket (``['') introduces a character class. The end of thecharacter class is indicated by a ``]''; if the ``]'' is missing thenthe ``['' matches a ``['' rather than introducing a character class.A character class matches any of the characters between the squarebrackets. A range of characters may be specified using a minus sign.The character class may be complemented by making an exclamation pointthe first character of the character class.

To include a ``]'' in a character class, make it the first character listed(after the ``!'', if any).To include a minus sign, make it the first or last character listed.By convention, the name ``/u/user'' refers to the home directory of thespecified user. There are good reasons why this feature should be supportedby the file system (using a feature such as symbolic links) rather thanby the shell, butashis capable of performing this mapping if the file system doesn't.If the mapping is done byash,setting the-fflag will turn it off.Ashsilently discards nul characters. Any other character will be handledcorrectly byash,including characters with the high order bit set.The termjobrefers to a process created by a shell command, or in the case of apipeline, to the set of processes in the pipeline. The ways to referto a job are:


The first form identifies a job by job number.When a command is run,ashassigns it a job number(the lowest unused number is assigned).The second form identifies a job by giving a prefix of the command usedto create the job. The prefix must be unique. If there is only one job,then the null prefix will identify the job, so you can refer to the jobby writing ``%''. The third form refers to the current job. Thecurrent job is the last job to be stopped while it was in the foreground.(See the next paragraph.) The last form identifies a job by giving theprocess id of the last process in the job.

If the operating system thatashis running on supports job control,ashwill allow you to use it.In this case, typing the suspend character (typically ^Z) while runninga command will return you toashand will make the suspended command the current job. You can then continuethe job in the background by typingbg,or you can continue it in the foreground by typingfg.If the shell variable ATTY is set, and the shell variable TERM is notset to ``emacs'', then ash generates appropriate escape sequencesto talk toatty(1).By tradition, an exit status of zero means that a command has succeededand a nonzero exit status indicates that the command failed. This isbetter than no convention at all, but in practice it is extremely usefulto allow commands that succeed to use the exit status to return informationto the caller. A variety of better conventions have been proposed, butnone of them has met with universal approval. The convention used byash and all the programs included in the ash distribution isas follows:

          0         Success.          1         Alternate success.          2         Failure.          129-...   Command terminated by a signal.
The alternate success return is used by commands to indicate variousconditions which are not errors but which can, with a little imagination,be conceived of as less successful than plain success. For example,testreturns 1 when the tested condition is false andgetoptsreturns 1 when there are no more options.Because this convention is not used universally, the-eoption ofashcauses the shell to exit when a command returns 1 even though thatcontradicts the convention described here.

When a command is terminated by a signal, the uses 128 plus the signalnumber as the exit code for the command.This concluding section lists the builtin commands which are builtinbecause they need to perform some operation that can't be performed by aseparate process. In addition to these, there are several other commands(catf,echo,expr,line,nlecho,test,``:'',andtrue)which can optionally be compiled into the shell. The builtincommands described below that accept options use the System V Release 2getopt(3)syntax.

[job] ...
Continue the specified jobs (or the current job if no jobs are given)in the background.This command is only available on systems with Bekeley job control.command arg...
Execute the specified builtin command. (This is useful when you have ashell function with the same name as a builtin command.)[directory]
Switch to the specified directory (default $HOME).If the an entry for CDPATH appears in the environment of the cd commandor the shell variable CDPATH is set and the directory name does notbegin with a slash, then the directories listed in CDPATH will besearched for the specified directory. The format of CDPATH is thesame as that of PATH.In an interactive shell, the cd command will print out the name of thedirectory that it actually switched to if this is different from thename that the user gave. These may be different either becausethe CDPATH mechanism was used or because a symbolic link was crossed.
The commands in the specified file are read and executed by the shell.A path search is not done to find the file because the directories inPATH generally contain files that are intended to be executed, not read.string...
The strings are parsed as shell commands and executed.(This differs from the System V shell, which concatenates the arguments(separated by spaces) and parses the result as a single command.)[command arg...]
Unlesscommandis omitted,the shell process is replaced with the specified program (which must be a realprogram, not a shell builtin or function).Any redirections on the exec command are marked as permanent, so that theyare not undone when the exec command finishes.If the command is not found, the exec command causes the shell to exit.[exitstatus]
Terminate the shell process. Ifexitstatusis given it is used as theexit status of the shell; otherwise the exit status of the precedingcommand is
The specified names are exported so that they will appear in the environmentof subsequent commands. The only way to un-export a variable is to unset it.Ashallows the value of a variable to be set at the same time it is exportedby writing

export name=value

With no arguments the export command lists the names of all exported variables.[job]
Move the specified job or the current job to the foreground.This command is only available on systems with Bekeley job control.optstringvar
The System Vgetoptscommand.-rvcommand...
The shell maintains a hash table which remembers the locations ofcommands. With no arguments whatsoever, the hash command printsout the contents of this table. Entries which have not been lookedat since the lastcdcommand are marked with an asterisk; it is possible for these entriesto be invalid.

With arguments, the hash command removes the specified commands fromthe hash table (unless they are functions) and then locates them.With the-voption,hashprints the locations of the commands as it finds them.The-roption causes thehashcommand to delete all the entries in the hash table except forfunctions.[job]
Print the process id's of the processes in the job. If the job argumentis omitted, use the current job.
This command lists out all the background processes which are childrenof the current shell process.[function-name]
The function name is defined to execute the last command entered.If the function name is omitted, the last command executed isexecuted again. This command only works if the-iflag is set.
Print the current directory. The builtin command may differ from theprogram of the same name because the builtin command remembers whatthe current directory is rather than recomputing it each time. Thismakes it faster. However, if the current directory is renamed, thebuiltin version of pwd will continue to print the old name for thedirectory.[-pprompt][-e]variable...
The prompt is printed if the-poption is specified and the standard input is a terminal. Then aline is read from the standard input. The trailing newline is deletedfrom the line and the line is split as describedin the section on word splitting above, and the pieces are assigned tothe variables in order. If there are more pieces than variables, theremaining pieces (along with the characters in IFS that separated them)are assigned to the last variable. If there are more variables thanpieces, the remaining variables are assigned the null string.

The-eoption causes any backslashes in the input to be treated specially.If a backslash is followed by a newline, the backslash and the newlinewill be deleted. If a backslash is followed by any other character,the backslash will be deleted and the following character will be treatedas though it were not in IFS, even if it
The specified names are marked as read only, so that they cannot besubsequently modified or unset.Ashallows the value of a variable to be set at the same time it is markedread only by writing

readonly name=value

With no arguments the readonly command lists the names of allread only variables.[{-options|+options|--}]arg...
Thesetcommand performs three different functions.

With no arguments, it lists the values of all shell variables.

If options are given, it sets the specified option flags, or clearsthem if the option flags are introduced with a+rather than a-.Only the first argument tosetcan contain options.The possible options are:

-e     Causes the shell to exit when a command terminates with
a nonzero exit status, except when the exit status of the command isexplicitly tested. The exit status of a command is considered to beexplicitly tested if the command is used to control anif,elif,while,oruntil;or if the command is the left hand operand of an ``&&'' or ``||''operator.

-f     Turn off file name generation.

-I     Cause the shell to ignore end of file conditions.
(This doesn't apply when the shell a script sourced using the ``.''command.) The shell will in fact exit if it gets 50 eof's in arow.

-i     Make the shell interactive. This causes the shell to
prompt for input, to trap interrupts, to ignore quit and terminate signals,and to return to the main command loop rather than exiting on error.

-j     Turns on Berkeley job control, on systems that support it.
When the shell starts up, the-jis set by default if the-iflag is set.

-n     Causes the shell to read commands but not execute them.
(This is marginally useful for checking the syntax of scripts.)

-s     If this flag is set when the shell starts up, the shell
reads commands from its standard input. The shell doesn't examine thevalue of this flag any other time.

-x     If this flag is set, the shell will print out each
command before executing it.

-z     If this flag is set, the file name generation process
may generate zero files. If it is not set, then a pattern which doesnot match any files will be replaced by a quoted version of the pattern.

The third use of the set command is to set the values of the shell'spositional parameters to the specifiedargs.To change the positional parameters without changing any options,use ``--'' as the first argument toset.If no args are present, the set command will leave the value of thepositional parameters unchanged, so to set the positional parametersto set of values that may be empty, execute the command

shift $#

first to clear out the old values of the positional parameters.variablevalue
Assignsvaluetovariable.(In general it is better to writevariable=valuerather than usingsetvar.Setvaris intended to be used in functions that assign values to variables whosenames are passed as parameters.)[n]
Shift the positional parametersntimes.A shift sets the value of $1 to the value of $2, the value of $2 tothe value of $3, and so on, decreasing the value of $# by one.If there are zero positional parameters, shifting doesn't do anything.[action]signal...
Cause the shell to parse and executeactionwhen any of the specified signals are received.The signals are specified by signal number.Actionmay be null or omitted;the former causes the specified signal to be ignored and the lattercauses the default action to be taken.When the shell forks off a subshell, it resets trapped (but not ignored)signals to the default action.The trap command has no effect on signals that were ignored on entryto the shell.[mask]
Set the value of umask (seeumask(2))to the specified octal value. If the argument is omitted, the umaskvalue is
The specified variables and functions are unset and unexported.If a given name corresponds to both a variable and a function, both thevariable and the function are unset.[job]
Wait for the specified job to complete and return the exit status of thelast process in the job. If the argument is omitted, wait for all jobsto complete and the return an exit status of zero. 


The following function redefines the cd command:

cd() {    if bltin cd "$@"    thenif test -f .enter    then. .enter    elsereturn 0    fi    fi}

This function causes the file ``.enter'' to be read when you enter adirectory, if it exists. The bltin command is used to access thereal cd command. The ``return 0'' ensures that the function willreturn an exit status of zero if it successfully changes to a directorythat does not contain a ``.enter'' file. Redefining existing commandsis not always a good idea, but this example shows that you can do it ifyou want to.

The suspend function distributed withashlooks like

# Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.# This file is part of ash, which is distributed under the terms# specified by the Ash General Public License.suspend() {    local -    set +j    kill -TSTP 0}

This turns off job control and then sends a stop signal to the currentprocess group, which suspends the shell. (When job control is turnedon, the shell ignores the TSTP signal.) Job control will be turned backon when the function returns because ``-'' is local to the function.As an example of what not to do, consider an earlier version ofsuspend:

suspend() {    suspend_flag=$-    set +j    kill -TSTP 0    set -$suspend_flag}

There are two problems with this. First, suspend_flag is a globalvariable rather than a local one, which will cause problems in the(unlikely) circumstance that the user is using that variable for someother purpose. Second, consider what happens if shell received an interruptsignal after it executes the first set command but before it executesthe second one. The interrupt signal will abort the shell function, sothat the second set command will never be executed and job controlwill be left off. The first version of suspend avoids this problemby turning job control off only in a local copy of the shell options. Thelocal copy of the shell options is discarded when the function is terminated,no matter how it is terminated. 


Shell variables can be used to provide abbreviations for things whichyou type frequently. For example, I set
export h=$HOME
in my .profile so that I can type the name of my home directory simplyby typing ``$h''.

When writing shell procedures, try not to make assumptions about what isimported from the environment. Explicitly unset or initialize all variables,rather than assuming they will be unset. If you use cd, it is a good ideato unset CDPATH.

People sometimes use ``<&-'' or ``>&-'' to provide no input to a commandor to discard the output of a command. A better way to do this isto redirect the input or output of the command to/dev/null.

Word splitting and file name generation are performed by default,and you have to explicitly use double quotes to suppress it. This isbackwards, but you can learn to live with it. Just get in the habit ofwriting double quotes around variable and command substitutions, andomit them only when you really want word splitting and file name generation.If you want word splitting but not file name generation, use the-foption. 


Kenneth Almquist 


echo(1), expr(1), line(1), pwd(1), true(1). 


When command substitution occurs inside a here document, the commands insidethe here document are run with their standard input closed. For example,the following will not word because the standard input of thelinecommand will be closed when the command is run:

cat <<-!Line 1: $(line)Line 2: $(line)!

Unsetting a function which is currently being executed may cause strangebehavior.

The shell syntax allows a here document to be terminated by an end of fileas well as by a line containing the terminator word which follows the ``<<''.What this means is that if you mistype the terminator line, the shellwill silently swallow up the rest of your shell script and stick itin the here document.




This document was created byman2html,using the manual pages.