Files
bash/doc/oldbash.texi
T
2011-12-03 12:52:47 -05:00

9292 lines
308 KiB
Plaintext

\input texinfo @c -*- texinfo -*-
@c %**start of header
@setfilename bash.info
@settitle GNU Bourne Again SHell
@setchapternewpage odd
@c %**end of header
@ignore
**EXPLANATION OF COMMENTS IN FILE**
All comments, which start with @c, are by Julie Sussman
(jems@zurich.ai.mit.edu).
If a comment has someone else's name or initials in it, it is still
by me (Julie), but is a note on something that person told me.
@end ignore
@ignore
**TO DO**
Update all nodes
Update all menus for Info. They don't match current manual.
Fix the cross references -- too many have abbreviated node names.
Fix/redo/complete the indexing.
Separate index for commands, vars, etc. (separate from concepts)
Use group/end group around examples to prevent bad page breaks.
@end ignore
@ignore
JEFF KELLEM'S MISC. COMMENTS
* add a glossary
* below are some additions/changes that are being considered for final
1.06 release -- there are probably others; these are off the top of my
head
* check on `-' arg to cd to swap $PWD and $OLDPWD
* `+' option to `set' to list all var names w/o their values (`set +')
* `set --' will unset the positional params if no other args are given ?
* -r option to read
* -p flag of jobs to list PIDs only (posix.2a)
* job_spec args to jobs (posix.2a)
* shell error msgs may now have `bash: ' as a prefix (will have to chk
if Brian decided to bless it)
@end ignore
@c DON'T RUN FINALOUT YET UNTIL FINAL STAGES
@ignore
@iftex
@finalout
@end iftex
@end ignore
@ifinfo
This file documents the GNU Bourne Again SHell.
Copyright @copyright{} 1989, 1990 Free Software Foundation, Inc.
@end ifinfo
@titlepage
@sp 10
@center @titlefont{Bourne Again SHell}
@center Unproofed Draft
@sp 10
@center Brian Fox, Diane Barlow Close,
@center Julie Sussman, Chet Ramey,
@center Richard Stallman
@center @today{}
@page
This document describes GNU Bash, a Bourne shell compatible command
language interpreter which executes commands read from standard input
or from a file.
Published by the Free Software Foundation @*
675 Massachusetts Avenue, @*
Cambridge, MA 02139 USA
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the Foundation.
@vskip 0pt plus 1filll
Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
@end titlepage
@node Top, Thanks, (dir), (dir)
@unnumbered Preface
This manual introduces the GNU Bourne Again SHell (BASH) and explains
its role in the operating system. This manual does not explain the
fundamentals of using operating system commands such as @code{ls},
@code{cd}, and others, nor does it explain how to log into your system.
BASH is a command language interpreter that executes commands read from
the standard input or from a file. BASH is compatible with the Bourne
shell (@code{sh}), and also incorporates useful features of the Korn
shell (@code{ksh}) and the C shell (@code{csh}). The intention is that
BASH be a superset of the desirable features found in other shells.
BASH is POSIX compliant.
If you read this manual sequentially, you'll find it leads you through
the concepts of a shell from its simple beginnings to more complex
shell features. If you are familiar with your machine's operating
system and have some experience with shells, then this manual makes a
handy reference.
@c A nice goal would be to make the above paragraph come true
@menu
* Thanks:: Acknowledgement of those who made it possible.
* License:: GNU licensing information.
* Introduction:: Introduction to shells.
* I/O:: Redirection. Pipes.
* Line:: Command line syntax.
* File Names:: How the shell interprets your input before
it arrives at other commands. Wildcard
characters.
* Job Control:: Controlling when commands are run.
* Editing:: Editing lines that you type, and how to
get at previously typed lines.
* History:: History substitution.
* Aliases:: Substitution of command words.
* Functions:: How to generalize a group of related
commands.
* Programming:: An overview of programming using BASH.
* Scripts:: Writing shell programs with BASH.
* Variables:: Shell variables.
* Environment:: Discovering your shell's environment.
* Conditionals:: Programming using conditional statements.
* Looping:: Programming using looping statements.
* Built-in:: Description of commands that are built into
the shell.
* Install:: Installing BASH.
* Invoke:: Invoking BASH. Details on signal control in BASH.
Customizing BASH prompts.
* Start-up:: A sample start-up files for BASH.
* Advanced Scripts:: Samples of writing more advanced shell scripts.
* Tools:: Related and useful operating system commands.
* Authors:: Who's responsible for all this.
* Concept Index:: Index of shell concepts.
@end menu
@node Thanks, , Top, Top
@unnumberedsec Acknowledgements
Many people need to be thanked for their assistance in producing this
manual. Brian and Diane would like to thank Chet Ramey for his
production of the BASH man page. It made the job of writing this
manual infinitely easier.
Robert Chassell gave helpful comments on the drafts of this manual.
Allan Painter contributed beginning-user examples. Bennett Todd
and Bill Trost contributed very useful samples of shell scripts. Many
thanks to all those who submitted scripts for consideration. It
was difficult to choose only two for inclusion in this manual; all were
of very high quality and usefulness.
@node License, Introduction, Top, Top
@unnumbered License
@node Introduction, Typing Commands, License, Top
@chapter Introduction to Shells
@c This chapter needs to be rewritten/replaced
@ignore
Some topics:
built-in cmds, other cmds, use in examples and doc in manual
@end ignore
The shell is a program that the operating system automatically starts
up when you log in, so that the system can understand your commands.
@cindex shell, what is a
@cindex BASH, what is
@cindex Bourne Again SHell, what is
Here is a brief listing of some of the things that the Bourne Again SHell
(BASH) provides:
@itemize @bullet
@item
a built-in language for writing shell programs
@item
compatibility with shell programs written for the Bourne shell
@item
Emacs and vi style command editing
@item
process and job control
@item
command aliases
@item
shell @emph{functions}
@item
completion of file names, user names, and variable names
@c "and other types of completion" ?? such as what??
@end itemize
@menu
* Interpretation:: The Shell as a Command Interpreter.
* Language:: The Shell as a Programming Language.
@end menu
@node Interpretation, Language, Introduction, Introduction
@section The Shell as a Command Interpreter
When you log on to your system a shell is automatically started for you.
Think of the shell as a layer of software between you and the operating
system's internal workings, as shown below:
@cindex command interpreter
@cindex shell, as a command interpreter
@example
@var{commands} (@r{typed by you}) <------> @var{shell} <-------> @var{operating system}
@end example
@noindent
The shell interacts with you, the user, to interpret your commands and
tell the operating system to take appropriate action. The shell stays
with you until you log out.
The input and execution of a simple shell command involves the following
steps:
@enumerate
@item
The shell displays a prompt (@samp{bash$}, unless you have
specified a different prompt) and waits for you to type a command.
@item
You type a command line, ending with a carriage return.
@item
The shell analyzes that command line, and extracts the command name
and arguments. Here is a template for a simple shell command, with
the optional parts between square brackets, @samp{@r{[}@dots{}@r{]}}:
@example
@var{command} @r{[}@var{arguments}@r{]} @r{[}&@r{]} @key{RET}@refill
@end example
@noindent
A simple command line consists of a sequence of words
separated by blanks (a blank is a space or a tab). The first word of
the command line specifies the name of the command to be executed, and the
remaining words are passed as arguments to that command.
@item
The shell tries to locate the specified command as a program in the
directories specified in your path.
@item
If the shell can't find the command program you requested, it gives you
an error message and provides a new prompt.
If the shell is successful in locating the requested program, it tells
the operating system to execute that program using the rest of the
command line as arguments for that program.
@item
If you did not end your command line with @samp{&}, the program is run
in the @dfn{foreground}. When the program is
finished, the operating system returns control to the shell and the
shell gives you another prompt.
If you ended your command line with @samp{&}, the program is run in the
@dfn{background}.While the program is executing the shell waits.
The shell doesn't wait for the operating system to
finish running the program; rather, the shell immediately gives you a prompt so
you can continue typing commands. (Running a program in the background
is useful if the program takes a long time to execute and doesn't need
supervision.)
@item
At the new prompt you type in the next command line to be processed
and run. These steps are repeated until you log out.
@end enumerate
@node Language, , Interpretation, Introduction
@section The Shell as a Programming Language
BASH has its own built-in, interpreted programming language.
@cindex shell, as a programming language
@cindex programming language, features
Some of the programming features available to you are:
@itemize @bullet
@item
storage of values in variables
@item
conditional execution statements
@item
user-defined functions
@item
looping and other ways of executing commands repeatedly
@end itemize
@node Notation
@section Notation
To indicate special keys or key combinations, this documentation
uses the following notations:
@c also explain RET, CTL, DEL, etc.
@table @kbd
@item C-k
The text @kbd{C-k} is read as ``Control-K'' and describes the character
produced when you hold the Control key (@key{CTL}) down and strike the @kbd{k} key.
@item M-k
The text @kbd{M-k} is read as ``Meta-K'' and describes the character
produced in either of two ways:
@itemize @bullet
Either hold the @key{META} key (if you have one) down and strike the @kbd{k} key
or type @key{ESC} @i{first} and then type @kbd{k}.
@end itemize
Either process is known as @dfn{metafying} the @kbd{k} key.
@item M-C-k
The text @kbd{M-C-k} is read as ``Meta-Control-k'' and describes the
character produced by metafying @kbd{C-k} (see @kbd{C-k} and @kbd{M-k}
just above).
@end table
@node Typing Commands, I/O, Introduction, Top
@chapter Typing Commands
@c !! forgot to cover case sensitivity!
This chapter deals with the mechanics of typing commands.
Normally, to give a command you type a line and end it with a newline
character (usually referred to as @key{RET} in this documentation).
In the following example, BASH displayed its prompt (@samp{bash$ }),
we typed the command @samp{who} (terminated by a @key{RET}, which is
not explictly shown in the example), the output of @code{who} (a listing
of users logged into the system) was displayed, and BASH displayed
another prompt.
@example
bash$ who
glassw ttyq0 Apr 15 15:09 (worker-8)
glassw ttyq1 Apr 15 20:50 (worker-7)
cqc ttyq2 Apr 15 18:15 (worker-9)
zvona ttyq5 Apr 15 14:13 (nico)
painter ttyd0 Apr 15 21:00
stf ttyh4 Apr 15 11:58
sandiway ttyh9 Apr 13 23:05
pwu ttyhc Apr 15 15:19
bash$
@end example
The following sections explain more about typing commands, including how
to correct mistakes as you type a command and how to type a command that
is too long to fit on one line.
@node Typeahead
@section Typeahead
Your typing is echoed (displayed on the screen) as you type.
If you start to type a command before the prompt is displayed,
your typeahead, which echoes immediately, appears before the
prompt. It may even be mixed up with output from the command
that was executing when you typed it.
In order that you can see the actual command you have
typed, BASH redisplays your typeahead after the prompt.
Don't worry -- though some characters appear on your screen twice,
BASH has kept only one copy of them.
The following shows the appearance of my screen when I
typed @samp{date} to find out the current date and time,
then typed @samp{who} to find out who was logged in.
I didn't wait for @code{date}'s output before I started to type,
so the @samp{wh} from @samp{who} appears in that output.
The next prompt is followed by a redisplay of the @samp{wh}
I already typed, followed by the final @samp{o}.
@example
bash$ date
whFri Jan 04 13:47:49 EST 1991
bash$ who
gjs console Dec 19 15:53
wisdom pty/ttyu0 Dec 27 16:11
jems pty/ttyu1 Jan 4 10:56
bash$
@end example
@node Editing, Continuation, Typing Commands, Typing Commands
@section Editing the Command Line
@cindex editing command lines, basic
To correct an error in the line you are typing, you can type @key{DEL}
repeatedly to delete one character at a time until you are back to the
spot that needs fixing, then continue typing. Or you can type @kbd{C-u}
to delete the whole current line and start over.
However, it is also possible to move the cursor to the place you want to
change and correct the error without deleting and retyping everything
you've typed after the error.
You can edit the current line as long as you have not typed the
@key{RET} that terminates it.
Using the editing keys described below, you move the cursor to the
place that needs correction and delete or insert the text of the
correction. Then, when you are satisfied with the line, you simply
press @key{RET}. The cursor doesn't have to be at the end of the line
when you press @key{RET}; the entire line will be accepted in any case.
As you type text into the line, you'll notice that characters to the
right of the cursor get pushed over to make room for the
characters you are typing. Likewise, when you delete a character
behind the cursor, characters to the right of the cursor get pulled
back to fill in the blank space created by the removal of those
characters.
The rest of this section describes basic command-line editing.
@xref{Readline Commands}, for a list of all the editing commands.
If you are an Emacs user, you may already be familiar with most of the
editing keys described below: All but @kbd{C-u} are the same ones used
in Emacs.
Note: If you don't like any of the editing keys, you can change them
to be whatever you want (@pxref{Customizing Readline}).
@heading Moving the Cursor
Here are the basic ways to move the cursor within the line you are typing:
@table @kbd
@item C-b
Move cursor back (left) one character.
@item C-f
Move cursor forward (right) one character.
@item M-b
Move cursor backward (left) one word.
@item M-f
Move cursor forward (right) one word.
@item C-a
Move cursor to the start of the line.
@item C-e
Move cursor to the end of the line.
@end table
Notice that @kbd{C-f} moves forward a character, while @kbd{M-f}
moves forward a word. It is usually the case that Control keystrokes
act on characters, while Meta keystrokes act on words.
@heading Deleting Text
Here are the basic ways to delete text once you have positioned the cursor:
@table @kbd
@item C-d
Delete the character underneath the cursor.
@item @key{DEL}
Delete the character to the left of the cursor.
@item C-k
Kill the text from the current cursor position to the end of the line.
@item C-u
Kill the text from the beginning of the line to the current cursor position.
(Note that if the cursor is at the end of the line, this kills the whole line.)
@end table
@c maybe add M-d, M-DEL (corresponding to C-d, DEL)
@heading Inserting Text
To insert text into the line, just position the cursor and type
the text as you normally do at the end of a line.
No special keystroke is needed to indicate that you want to insert.
@heading Clearing the Display
If the screen is cluttered, you may wish to:
@table @kbd
@item C-l
Clear the screen, reprinting the current line at the top.
@end table
@node Typos
@subsection Failing to Correct a Command Line
If you notice an error while typing a command, it is better to
fix it (or delete the command and start over) than to let the command
execute as is, especially if the command contains any punctuation
characters (many of which have special meaning to the shell).
Although many sorts of errors will result in perfectly harmless
(and sometimes even comprehensible) error messages, other erroneous
commands may do things you didn't intend or give you error messages that only
a shell wizard can understand.
For example, if you accidentally hit @samp{*} while typing a file
name in a command to delete a file, you may end up deleting more
than one file (@pxref{File Names}).
@node History Use
@section Repeating Earlier Commands
You can sometimes save typing by retrieving an earlier command.
You can reexecute the command as is, or you can edit it before
executing it.
This is particularly useful if a command gets an error.
Instead of retyping it with the error corrected, you can
retrieve the command and just fix the erroneous part.
If you are an Emacs user, you may recognize the following commands
as the same ones that move to the previous or next line
or to the beginning or end of an Emacs buffer.
Think of BASH as maintaining an Emacs buffer of your command
lines, in which you can see only one line at a time.
Each time you end a line (by typing @key{RET}), BASH adds
that line to the end of the buffer and positions its cursor
at the start of the next line.
@xref{History List}, for a more complete description of what
commands BASH remembers in its history list.
The rest of this section describes the basic commands for accessing
previous command lines.
@xref{History Commands}, for the complete set of commands.
@c note: the stored line contains the result of history substitutions.
@c If you typed a ! history reference, the resulting cmd is stored.
@c because: history subst is before shell sees input
@c Following edited from readline chapter -- may need to change that to
@c match this.
@table @kbd
@item C-p
Get the previous line from the history list.
(Opposite of @kbd{C-n}.)
The line is displayed after the prompt as if you had just typed it.
@item C-n
Get the next line from the history list.
(Opposite of @kbd{C-p}.)
The line is displayed after the prompt as if you had just typed it.
@item M-<
Get the oldest line in the history list.
(Opposite of @kbd{M->}.)
The line is displayed after the prompt as if you had just typed it.
@item M->
Get the most recent line in the history list.
(Opposite of @kbd{M-<}.)
This is the line you are typing at the current prompt.
Unless you type something after the prompt, this line is blank.
@end table
If you're a BASH novice, it is probably best to start by using
just @kbd{C-p} and @kbd{C-n}.
Type @kbd{C-p} repeatedly to move back as far as you want.
If you overshoot, use @kbd{C-n} to go forward again.
@node Continuation, , Editing, Typing Commands
@section Continuing a Command on the Next Line
If you don't have room on the line to finish typing your command,
type a backslash, @samp{\}, then @key{RET}.
A @samp{\} at the @emph{end} of a command
line tells the shell that the command hasn't ended, but is to be
continued on the next line.
The shell will give you a secondary prompt (different from the ordinary
prompt, so you can tell that this is a continuation line), and you can
continue typing the rest of the command.
In this way, you can continue a command over any number of lines.
The command is not executed until the final @key{RET} (that is, a @key{RET}
not preceded by a @samp{\}) is typed.
@c But: expansion/substitution take place after each RET -- e.g. !, *, ...
@c rms: ! is during input processing by history library, * is done by shell
@c bfox: ! done on each line
@c can avoid \ if know what's incomplete
@c e.g. things in quotes
@c usually only use \ for shell script, don't need interactively
@c a) usually type shorter cmds, b) line will wrap
@c consider moving this? or recommending really for scripts and describing
@c the default long-line wraparound (with pointer to inputrc for
@c changing it)
@cindex long commands
@cindex continuing command lines
@cindex command lines, continuing
@cindex commands longer than 1 line
@c lousy example
For example, both of the following commands concatenate the files
@file{file1} through @file{file6} together into a single file
@file{file1to6}. In the first sequence, the command is split into two
lines by ending the first line with a @samp{\}. BASH prints a secondary
prompt (@samp{bash>}, unless you have specified a different prompt) to
signal that it awaits further input for the current command.
@example
bash$ cat file1 file2 file3 \@key{RET}
bash>file4 file5 file6 > file1to6@key{RET}
bash$
@end example
@noindent
is equivalent to:
@example
bash$ cat file1 file2 file3 file4 file5 file6 > file1to6@key{RET}
bash$
@end example
Warning:
@itemize @bullet
@item
The @samp{\} must be the last thing on the line that is to be
continued. If you accidentally type a space after the @samp{\}, your
screen will not look any different, but the command line will be
terminated by the @key{RET} rather than continued.
@item
The multiple command lines are simply concatenated, with no
space inserted. If a space is needed between the last thing you type
on one line and the first thing you type on the next line, you must
be sure to include the space yourself (either before the @samp{\}
that ends the first line or at the start of the next line).
@end itemize
@heading Editing Earlier Lines
Command-editing (@pxref{Editing}) only works on the current line.
If you notice while typing a continuation line that you need to correct
an earlier line of the command, you will need to abort the command
entry and start over (though you needn't retype everything, if you
follow the instructions below):
@enumerate
@item
To avoid losing the line you are in the midst of typing, end it with
@kbd{\@key{RET}}.
@item
Type @kbd{C-c} to abort command entry and get back to the top level of
BASH.
@item
The lines you typed but never executed were nonetheless stored
in the command history list. Use @kbd{C-p} (@pxref{History Use})
to retrieve the lines of your multi-line command one at a time.
Type @key{RET} after each correct line, but when you come to the bad
line, edit it before typing @key{RET}.
@end enumerate
@node I/O, File Names, Typing Commands, Top
@chapter Redirecting Input and Output (Basic)
@cindex redirecting input and output
You may want to send a program's output to a printer instead
of to your screen. Or you may want to use a data file for
input, instead of typing input at your keyboard.
@cindex redirection operators, versus command arguments
Many commands
allow input files and output files to be specified as arguments.
For commands that don't take such arguments (or whose arguments you
don't remember), you can use redirection operators, as
explained in this chapter, to @dfn{redirect} input or output to come
from or go to a file.
You can also redirect input or output to come from or go to another
program, by using @dfn{pipes}.
Redirection is performed by the shell, not by individual command programs.
The action of the command itself is unchanged by redirection; in
general, commands are unaware that their input or output has been redirected.
The command reads its input and writes its output as usual, and that
input and output automatically come from and go to whatever places the shell has set up.
This is accomplished as follows.
@cindex standard input
@cindex standard output
@cindex standard error
Most programs that read from or write to the terminal actually
read their input from an imaginary place called
@dfn{standard input}, write their ordinary output to an imaginary
place called @dfn{standard output}, and write their error messages
to an imaginary place called @dfn{standard error}.
Before the shell runs the program in a command, it hooks up the
standard input, standard output, and standard error to real places,
such as your terminal, a file, or another program's input or output.
The following sections tell you how to specify how these standard
input and outputs should be hooked up.
@c add a diagram showing standard I/O as sockets with things plugged in?
@heading Redirection versus file arguments
@cindex redirection operators, versus command arguments
Consult the documentation of the specific command you wish to use to
see whether you have to use redirection operators in order to make it
use files.
File Names as
arguments are often preferable to redirection operators because they enable
the command to know the name of the file it is reading. (A command can
know its arguments, but is not aware of redirection.) Also,
some commands (such as @code{sort})
can read more than one input file when the files are
specified as arguments, whereas redirection can only specify a single input
file.
@c If file args to cmd are preferable, isn't it bad to use such cmds as
@c redirection examples?
@ignore
rms: better examples: cat, compress
compress file
replaces file with file.Z and deletes original file
option to not delete file
If want to redirect output, must redirect input too.
compress < f1 > f2
Because if there's an arg (file name), compress
opens the arg file itself, so redirection is useless.
With no arg, it uses streams it's given (by < and >)
@end ignore
For example, here are two ways to sort the file @file{unsorted}
to produce the file @file{sorted-file}.
The first command gives the file names as arguments, with @samp{-o}
flagging the output file name.
The second command uses @samp{<} to redirect the input and @samp{>}
to redirect the output.
@example
bash$ sort -o sorted-file unsorted
bash$ sort < unsorted > sorted-file
@end example
@noindent
However, if you want to combine two input files @file{unsorted-1}
and @file{unsorted-2} into one sorted output file, you'll have
to give the input files as arguments, because only one input file
could be supplied by redirection. You still have a choice of how to
specify the output file.
@example
bash$ sort -o sorted-file unsorted-1 unsorted-2
bash$ sort unsorted-1 unsorted-2 > sorted-file
@end example
@menu
* Redirection:: How to redirect standard input and standard
output.
* Other Redirections:: Redirecting standard input and standard output
simultaneously. Redirecting background
processes. Redirecting standard error.
* Pipes:: Connecting commands together.
@end menu
@node Redirection, Here-documents, I/O, I/O
@section Basic Redirection to Files
@c posix 3.7 n op word
@c op is: < > >| >> << <& >& <>
@c special cases for <&-, >&-, <<-
@cindex redirection operators
@cindex standard input, redirecting
@cindex standard output, redirecting
@cindex standard error, redirecting
This section shows the basic method for redirecting the standard input,
standard output, and standard error to files.
@xref{Advanced Redirection}, for more complicated forms of redirection.
@c may want appendix that has 1 unified table of operators
In general, a simple redirection of input or output to a file looks like this:
@c rms: redir op can be among or before args (even before cmd?) [see posix]
@ignore
@c They were each shown with args, but it's probably better to consider
@c those as part of the command. E.g. it was:
@var{command} @r{[}@var{arguments}@r{]} > @var{file}
@end ignore
@example
@var{command} @var{redirection-operator} @var{file}
@end example
@c show syntax for more than 1 redir op in a cmd??
@noindent
The @var{file} is the file or device you want to use,
@c note: "file" includes "devices" (such as printers). Explain somewhere?
@c Nice thing in Unix is devices are simply files in directory /dev
and the @var{redirection-operator} is @samp{<} for input; @samp{>}, @samp{>|},
or @samp{>>} for output; or @samp{>&} for output and error.
Spaces surrounding the operator are optional, but it is a good idea
to leave a space before the operator.
(Otherwise you might accidentally specify one of the redirections
with a file descriptor -- @ref{Advanced Redirection}.)
@c Space needed after arg if it is a # and could look like file-descr.
@c rms: spaces optional around the REDIRECTION, but required to avoid ambig.
@ignore
In this section, with no file descriptor before operator (i.e. file
descriptor defaulted) and file name required after each operator, the
operators are as follows:
> >| >> < posix
>& bash extension (from csh)
(posix doesn't define >& with file name)
Anything involving a file descriptor or no file name is considered advanced.
@end ignore
@table @code
@item >
@itemx >|
@itemx >>
instruct the shell to send the command's standard
output to the specified @var{file} instead of to your terminal.
@cindex @code{>} operator, redirecting output
@cindex @code{>>} operator, redirecting output
@c copy of following itemize is in advanced chapter
@itemize @bullet
@item
If @var{file} doesn't yet exist, it is created.
@item
If @var{file} already exists:
@itemize @bullet
@item
With @samp{>} and @samp{>|}, @var{file} is erased before the
first output is written to it. Be careful:
If a file of the same name already exists,
its contents are deleted before your command's output is
written to that file.
If you don't want @samp{>} to erase existing files, set the
shell's @code{noclobber} variable; then
@samp{>} with an existing file will generate an error message and leave
the file alone. (But note that @samp{>|} will clobber existing files
regardless of the setting of the @code{noclobber} variable.)
@c Note: alternative 'set -o noclobber...' for noclobber var -- where
@c should cover this? which is preferable?
@item
With @samp{>>}, the output is appended to the end of an existing @var{file}.
@end itemize
@end itemize
Note that @samp{>}, @samp{>|} and @samp{>>} redirect only the standard
output; error messages printed by @var{command}, which go to standard
error, still appear on the terminal and not in the file @var{file}. To
redirect error messages along with other output, see @samp{>&}, below.
Here's an example of output redirection:
@example
bash$ who
glassw ttyq0 Apr 15 15:09 (worker-8)
glassw ttyq1 Apr 15 20:50 (worker-7)
cqc ttyq2 Apr 15 18:15 (worker-9)
zvona ttyq5 Apr 15 14:13 (nico)
painter ttyd0 Apr 15 21:00
stf ttyh4 Apr 15 11:58
sandiway ttyh9 Apr 13 23:05
pwu ttyhc Apr 15 15:19
bash$ who > users-file
bash$
@end example
@noindent
The command @code{who} prints onto standard output a list of
the users currently logged into a computer system.
The simple command @samp{who}
prints onto your screen (the default standard output). The
command @samp{who > users-file} redirects @code{who}'s
standard output to
the file @file{users-file}, so that the output of the @code{who}
command goes into @file{users-file}
instead of appearing on the screen.@refill
The following command sequence creates a file containing the current
date followed by the list of users currently logged onto the system:
@example
bash$ date > date-who-file
bash$ who >> date-who-file
bash$ cat date-who-file
Sat Aug 04 11:27:05 EDT 1990
glassw ttyq0 Apr 15 15:09 (worker-8)
cqc ttyq2 Apr 15 18:15 (worker-9)
zvona ttyq5 Apr 15 14:13 (nico)
painter ttyd0 Apr 15 21:00
stf ttyh4 Apr 15 11:58
pwu ttyhc Apr 15 15:19
bash$
@end example
@noindent
The command @code{date} prints the system date on standard output.
In this example, the output of @code{date} becomes the first line of the file
@file{date-who-file} created with the @samp{>} redirection operator.
The output of the @code{who} command is @emph{appended} to the file
@file{date-who-file}, because we used the @samp{>>} redirection
operator. @code{cat} simply shows the file's contents on the terminal.@refill
@item &>
@itemx >&
both instruct the shell to send the command's
standard output @emph{and} standard error to the file @var{file},
instead of to your terminal. Both ordinary output and any error
messages are written to @var{file}, interspersed, in the order they
are generated. Of the two forms, the second (@code{>&}) is preferred,
because it conforms to the convention that output redirection operators start
with @samp{>}.
@cindex @code{>&} operator, redirecting output
@cindex @code{&>} operator, redirecting output
As with @samp{>}, @var{file} is erased before the first output is written to
it. Be careful:
If a file of the same name already exists, its contents are deleted
before your command's output is written to that file.
If you don't want @samp{>&} to erase existing files, set the
shell's @code{noclobber} variable; then
@samp{>&} with an existing file will generate an error message and leave
the file alone.
@c no appending version of >& analogous to >> -- suggested it to bfox
The example at the end of this section shows how to redirect
standard error and standard output to different places.
@item <
instructs the shell to get the command's standard input from the
specified file @var{file} instead of from your terminal.
@cindex @code{<} operator, redirecting input
Here's an example of this type of redirection:
@example
bash$ wc < date-who-file
7 39 244
bash$
@end example
@noindent
The command @code{wc} counts the number of lines, words, and
characters it reads from standard input. Using the standard input
redirection operator, @samp{<}, we made @code{wc} read a file as its
standard input. In this example, @code{wc} prints the line, word, and
character counts for the file @file{date-who-file} that was created in the
example for @samp{>>} above using the @code{date} and @code{who} commands.
Actually, redirection was not necessary for the above command,
since @code{wc} accepts the name of an input file as an argument:
@example
bash$ wc date-who-file
7 39 244
bash$
@end example
@end table
@cindex redirection operators, using more than one
More than one redirection operator can appear in a command.
Here's an example that redirects both standard input and standard output:
@example
bash$ sort < users-file > sorted-list
@end example
@noindent
This example reads the input for the command @code{sort} from the file
@file{users-file} and writes the sorted output to the file
@file{sorted-list}. Any error messages are still written to the
default standard error, which is your terminal screen.
You cannot redirect a single I/O stream to more than one file:
If you specify more than one redirection of the same I/O stream,
only the rightmost takes effect.
(The shell evaluates redirection operators in the order encountered, from
left to right.) For example, the output of @code{sort} in the following
goes only to @file{out-file}, not to @file{sorted-list}.
@example
bash$ sort < users-file > sorted-list > out-file
@end example
In the next example, the output of @code{sort} goes to @file{out-file}
and the error messages go to @file{error-file}. The @samp{>&} redirects
both standard output and standard error, then the @samp{>} redirects
standard output to @file{out-file}, overriding the @samp{>&}.
@example
bash$ sort < users-file >& error-file > out-file
@end example
@node Pipes, Pipes, Other Redirections, I/O
@section Pipes -- ``Mix-and-Match'' Commands
@c pipes are what connect processes, pipeline is whole thing
@c check terminology throughout
@cindex pipe
@cindex pipeline
@cindex pipes
@cindex @code{|}, use in piping
@cindex intermedate file, using pipe to avoid
@cindex combining commands with pipes
@cindex connecting commands together with pipes
@c a picture of boxes piped together would be nice
One of the shell's most powerful features is the way it lets you ``mix
and match'' commands. By feeding the output of one command into another
command, you can get a combination of behaviors that no predefined
command provides.
A @dfn{pipe} connects the standard output of one command to the standard
input of another.
This has the same effect as redirecting the standard output of the first
command to a file, then redirecting the standard input of the second
command to come from that file; but the pipe does this with a single
command, and stores no intermediate files on disk.
@c also: separate processes means output produced before 1st cmd finishes
For example, let's say you want to see an alphabetical list of the
users logged into the system.
There is no command that does this, but there is a command
@code{who} that produces a list of the logged-in users and
a command @code{sort} that sorts its input lines.
By piping these commands together
(making the output of @code{who} become the input to @code{sort}),
you can get the desired sorted list:
@c contrast with who > file; sort < file
@ignore
@c the raw data before sorted
@example
bash$ who
glassw ttyq0 Apr 15 15:09 (worker-8)
glassw ttyq1 Apr 15 20:50 (worker-7)
cqc ttyq2 Apr 15 18:15 (worker-9)
zvona ttyq5 Apr 15 14:13 (nico)
painter ttyd0 Apr 15 21:00
stf ttyh4 Apr 15 11:58
sandiway ttyh9 Apr 13 23:05
pwu ttyhc Apr 15 15:19
@end example
@end ignore
@example
bash$ who | sort
cqc ttyq2 Apr 15 18:15 (worker-9)
glassw ttyq0 Apr 15 15:09 (worker-8)
glassw ttyq1 Apr 15 20:50 (worker-7)
painter ttyd0 Apr 15 21:00
pwu ttyhc Apr 15 15:19
sandiway ttyh9 Apr 13 23:05
stf ttyh4 Apr 15 11:58
zvona ttyq5 Apr 15 14:13 (nico)
bash$
@end example
@heading Viewing Output by the Screenful
@cindex @code{more}, with pipes
@cindex pipe, used to view output by the screenful
An extremely important use for pipes is to view the output of a command
one screenful at a time, by piping the command's output into the
@code{more} command.
Let's say you want to see a detailed listing
of a directory that contains a large number of files. If you just
type @samp{ls -l}, the listing will scroll by faster than you can read it.
But if you use a pipe to attach the standard
output of @samp{ls -l} to the standard input of the @code{more}
command, you can page through the directory listing at your leisure:
@example
bash$ ls -l | more
@end example
@node How to pipe
@subsection How to Pipe Commands
@cindex pipeline, general format
To pipe the output of one command into the input of another, place a
vertical bar, @kbd{|}, between them. The general format for a
@dfn{pipeline} is:
@example
@var{command} | @var{command2} @r{[}| @dots{} @r{]}
@end example
@noindent
That is, any number of commands are given, separated by vertical bars,
@kbd{|}.
The standard output of @var{command1} is connected to the standard
input of @var{command2}, and so on.
In order for a pipeline to work, the first command in the pipeline
must generate output to the standard output,
the last command must accept input from the standard input, and
any intermediate commands must both read from standard input
and write to standard output.
@c rms: "filter" terminology good to know, standard terminology
@c for program designed to be used in a pipeline.
@c Many unix cmds designed so CAN be used as filter (i.e.they use
@c standard input and standard output)
Commands used between pipe operators are called @dfn{filters}. They
accept input from the standard input and generate output to
the standard output.
Examples of commands that can be used as filters
include @code{sort} (which sorts its input lines) and
@code{pr} (which formats text for printing).
@menu
* tee:: Using the @code{tee} command to preserve the
contents of intermediate files.
@end menu
@node tee, tee, Pipes, Pipes
@subsection Saving Intermediate Pipeline Data with @code{tee}
@cindex pipeline, @code{tee} in
@cindex @code{tee} command for pipelines
@cindex pipeline, saving intermediate data
Normally, any data generated by commands in a pipeline exists only
momentarily within the pipeline, because the output of each command
simply flows into the next command.
The command in the following example outputs the five lines of
the file @file{list-files} that come first alphabetically:
@example
bash$ sort list-files | head -5
@end example
@noindent
This works as follows:
The command @code{sort list-files} sorts the file, sending the sorted
data to the command @code{head -5}, which outputs the first five
lines in its input. The sorted data is discarded.
If you want to preserve the sorted data, you could first @code{sort} the
original data into a new file, then look at the @code{head} of that file:
@example
bash$ sort list-files > sort-saved
bash$ head -5 < sort-saved
@end example
@c pipe vs. redirection -- any pros or cons?
On some systems,
there is also a way to preserved the sorted data while using a pipeline.
To preserve intermediate pipeline data, such as the sorted data
in the above example, insert the @code{tee} command into your pipeline.
(Note: @code{tee} is not built into BASH. It comes with GNU, and may
or may not exist on other operating systems.)
@c bfox says: tee doesn't belong here (no non-shell cmds do)
@c including tee vs. including ps:
@c ps comes with unix, behavior varies from system to system
@c not all systems have tee -- though gnu will
@c jems thinks tee should be kept here
The @code{tee} command takes a file name as its argument and does two things:
@itemize @bullet
@item
It copies its standard input to the standard output.
@item
It copies its standard input into the specified file.
If the file doesn't exist, @code{tee} creates it.
If the file already exists, @code{tee} overwrites it,
unless you give @code{tee} the @code{-a} option, in which case
it appends to the file.
@c If tee arg omitted: It's a NOP: no err msg, no tee output
@c bfox: reason is so following will ``work'' even if var has no value
@c cmd 1 | tee $var | cmd2
@end itemize
@noindent
(The name @code{tee} stands for the T shape of a pipe used in plumbing
to split the flow into two parts.)
Thus @code{tee} can be used to copy the data passing through a pipeline
into a file for later use. For example, we can insert a @code{tee} into
the pipeline shown above:
@example
bash$ sort list-files | tee sort-saved | head -5
@end example
@noindent
Now the output of @code{sort} is sent to the @code{tee} command, which
stores the sorted data in a file called
@file{sort-saved} and also passes that data on to the next
program in the pipeline, @code{head}
@c diagram of example would be nice
@c list_files -> sort -> sorted data -> head -> lines on terminal
@c where sort and wc are in boxes
@node Pipes and redirection
@subsection Redirection in Pipelines
You may redirect the standard input of the first command in a pipeline
and the standard output and standard error of the last command in a pipeline
by using redirection operators (@pxref{Redirection}) in those commands.
The following example sorts the file @code{list-files}
(given to @code{sort} on its standard input by redirection with @code{<}),
gives the sorted output to @code{head}
(by connecting the standard output of @code{sort} to the standard input
of @code{head} with a pipe, @code{|}),
and stores the first five lines of the sorted output in the file @file{5lines}
(by redirecting the standard output of @code{head} to that file with @code{>}):
@example
bash$ sort < list-files | head -5 > 5lines
@end example
@node Pipeline processes
@subsection Processes in a Pipeline
@c new concepts: process, exit status
Each command in a pipeline is run as a separate process.
That is, the commands run simultaneously, in parallel.
The shell waits for all commands in the pipeline to terminate before
returning control to you.
The exit status of the pipeline is the exit status of the last command.
@node File Names, Customization, I/O, Top
@chapter File Names: Shorthands and Special Characters
@c need better title
@c need intro to material in chapter
@c new topic for bash 1.07 will go here: filename expansion
@c 'foo{a,b}' ==> 'fooa foob'
@node Wildcards
@section Wildcards
@c Wildcards also show up in Case statement patterns
@c rms: right to think of wildcards as being for file names
@c (case statement is strange additional use)
The shell allows you to specify sets of file names using @dfn{filename
patterns} containing @dfn{wildcard characters}, so that you don't have
to type all of the file names directly.
@cindex file names, wildcards in
@cindex wildcard characters in file names
For example, if you want information about the five files in the
current directory that end with @samp{.c}, you don't have to type
the five file names:
@example
ls -l foo.c bar.c fred.c card.c game2.c
@end example
@noindent
Instead you can type:
@example
ls -l *.c
@end example
@noindent
The shell interprets the filename pattern @samp{*.c} as matching all
existing file names ending in @samp{.c}. The character @samp{*}, which
can match almost any substring of a file name, is
called a wildcard character.
@xref{Wildcard Constructs}, for an explanation of @samp{*} and the other
wildcard constructs.
A single pattern may contain more than one wildcard.
For example, @samp{*.c*} would match all file names that contain
@samp{.c}.
@c document 'set -o noglob...' for disabling wildcards -- disables all
@c of them?
@node Wildcard Constructs
@subsection Wildcard Constructs
Here are the wildcard constructs and their meanings:
@table @code
@item *
The asterisk matches any sequence of zero or more characters, except
that it does not match a period at the beginning of a file name.
(If you want @samp{*} to include initial periods, set the variable
@code{glob_dot_filenames}.)
For example: @samp{foo*} matches any file name whose first three
characters are @samp{foo}, including the name @file{foo} itself;
@samp{*foo} matches any file name not starting with @samp{.} whose last
three characters are @samp{foo}, including the name @file{foo} itself;
and @samp{.*foo} matches any file name starting with @samp{.} whose last
three characters are @samp{foo}, including the name @file{.foo} itself;
@c Beware! .* can behave unexpectedly
@c ls .* expands to ls . .. .emacs (and so on)
@c but ls . and ls .. list those directories!
@c by contrast, *. behaves as expected (* can't match initial .)
@item ?
The question mark matches any single character, except
that it does not match a period at the beginning of a file name.
(If you want @samp{?} to match initial periods, set the variable
@code{glob_dot_filenames}.)
For example, @samp{foo?} matches any four-character file name
whose first three characters are @samp{foo}. (Note that @samp{foo?}
does not match @samp{foo} because @samp{foo} has only three characters.)
@item [@var{char-set}]
This @dfn{character set} matches any @emph{one} character specified by
the @var{char-set}.
Like a @samp{?}, a character set matches a single character. Unlike the
@samp{?}, the character set is selective about which characters it will match.
The @var{char-set} consists of a sequence of any number of characters
and/or any number of ranges of characters.
The character set matches any of the single characters listed or any of
the characters included in the specified ranges.
For example, @samp{[123abcdq]} will match any one character from
the set @samp{123abcdq};
@samp{[1-3a-dq]} matches exactly the same characters, but it uses
hyphens to indicate the ranges of characters from @samp{1} to @samp{3}
(inclusive) and from @samp{a} to @samp{d}.
Thus, @samp{foo[12]} matches @samp{foo1} and @samp{foo2} and nothing else;
@samp{foo[a-z]} matches any four-character file name whose
first three characters are @samp{foo} and whose fourth
character is any lower-case letter; and
@samp{foo[a-z12]} matches any four-character file name whose
first three characters are @samp{foo} and whose fourth
character is @samp{1}, @samp{2}, or any lower-case letter.
@c KELLEM added ^ item (as synonym for !)
@item [^@var{char-set}]
This matches any @emph{one} character @emph{not} included in the given
@var{char-set}, where the @var{char-set} is as specified above for
the @code{[@var{char-set}]} case.
For example, @samp{foo[^a-z12]} matches any four-character file name whose
first three characters are @samp{foo} and whose last character is not
@samp{1}, @samp{2}, or a lower-case letter.
@item [!@var{char-set}]
This is the same as @code{[^@var{char-set}]} if history substitution
is disabled.
Otherwise the @samp{!} invokes history substitution (@pxref{History}).
@c 12/90, Bash 1.06.25: 'ls b[!a]*' --> 'a]*: Event not found'
@c in particular, ! does history subst and [, ]*, are not interpreted here
@c because ! done before shell sees line
@c Tried quoting the ! -- ls fo[\!a] -- but it just said fo[!a] not found.
@c (didn't find my file 'foo')
@c Works with history disabled
@end table
@node Wildcard implementation
@subsection How Wildcards Work
Each command word that contains a wildcard character is @dfn{expanded},
which means it is replaced by a sequence of words, one for each
file that matches the pattern.
If @samp{*.c} in the command @samp{ls -l *.c} expands to
@samp{foo.c bar.c fred.c card.c game2.c},
the @code{ls} command sees these five file names as its arguments;
it never sees the @samp{*.c}.
Normally, a filename pattern that doesn't match any files is left in the
command as is (it expands to itself). For example, @samp{*.foo} is left
as is if there are no files ending in @samp{.foo}, so in the following
example the @code{ls} command gets @samp{*.foo} as its argument
and reports that there is no such file (which is what you want to know).
@example
bash$ ls -l *.foo
*.foo not found
bash$
@end example
@noindent
If for some reason you don't like this behavior, you can set the
variable @code{allow_null_glob_expansion}. When that variable is set, a
pattern that doesn't match anything is removed from the command (expands
to a null file name). In the above example, the @samp{*.foo} would
disappear, and @code{ls} would get no arguments, so it would report
on all files in the current directory.
Warning: A command word containing a wildcard construct is expanded
to a sequence of file names @emph{whether or not you intended it to be
a file name}. At the time the expansion takes place, the system does
not know or care whether it makes sense to treat the word as a file name.
@node echo, Quotation, File Names, File Names
@section Using @code{echo} to Preview Wildcard Expansion
If you are going to use wildcards for something dangerous, like deleting
a group of files, it is a good idea to be sure you know what files the
pattern will match.
@cindex @code{echo} command
@cindex command lines, previewing
To find out how wildcard characters will be expanded without actually
executing your command, use the @code{echo} command to preview the
expansion of a filename pattern. The @code{echo} command
simply displays its arguments fully expanded, with
any pattern that doesn't match anything left as is
(or deleted, if you have set @code{allow_null_glob_expansion} --
@ref{Wildcard implementation}).
@c rms: expand = replacing text with other text (!, *, ...)
@c interp may be part of expand,
@c e.g. substituting result of cmd into enclosing cmd
@c NB: $(...) is new version of `. Nice because it nests
For example,
@example
bash$ echo rm *.log *.foo
rm bash.log *.foo
bash$
@end example
@noindent
shows that if I ask to delete (with the @code{rm} command) all files
ending in @samp{.log} or @samp{.foo}, I will be deleting only
@file{bash.log}.
The pattern@samp{*.log} was expanded to the single file name that matched, namely
@samp{bash.log}, and @samp{*.foo} was not expanded because it did not
match any existing file names.
@c what is echo for besides wildcards & variable substitution?
@c rms: in shell scripts to print output
@c Not so good for ! expansion:
@c I tried 'echo !n' where n is a command #
@c It echoed with the ! expanded, namely it display 'echo ...'
@c Then it went on to execute that last 'echo ...' ???
@c Ah: the 'echoing' of the expansion is just the normal ! expansion,
@c not the execution of the 'echo !n' command. First the shell displays
@c the expanded command, then it executes it. So echo is a confusing
@c way to preview ! expansion.
@node Wildcard Quotation
@section File Names Containing Special Characters
@cindex wildcards, quoting
@cindex quoting, special characters in file names
Normally, file names are made up of ``ordinary'' characters --
alphanumeric characters (letters and numbers), periods (@samp{.}), and a
few other characters (such as @samp{_} or @samp{~}) that have no special
meaning to the shell. For example: the file containing this documentation is
named @file{bash.texinfo}; a backup version of this file saved for me by
Emacs is called @file{bash.texinfo.~1~}; and the file in which BASH
keeps track of commands I have issued (@pxref{History List}) is called
@file{.bash_history}.
If a file name contains a `special'' character -- a character that
has special meaning to BASH, you must @dfn{quote} it to prevent
BASH from giving the character its special interpretation.
In particular, you must quote the following characters if you need
to include them in a file name:
@example
! | & ; < > ( ) $ ` ' " \ * ? [ ] #
@end example
@c above is all special chars? what about : { } (others?)
@c rms: colon not special, braces are
@c bfox: should quote the braces in file ames
@c I tried it 1/31/91: foo} was not special, foo{ gave message about
@c missing } but then went on to process foo{
@c bfox: braces recognized as special only if separated from surrounding text
@c bourne:if not delimited, brace is regular char
@c bfox 2/8/91
@c New bash feature (stole from csh): foo{a,b} ==> fooa foob
@c Will fix to not treat { as brace expansion unless see a comma
@xref{Quotation}, for information on how to quote.
@node Tilde
@section Tilde Expansion
You can avoid having to type long directory pathnames by using a
shorthand for your home directory (and even other users' home
directories) and for the directory you were last connected to.
All of these directory abbreviations start with @kbd{~}.
You may also see this home-directory shorthand in program output.
For example, when you ask Emacs to find a file,
it uses @kbd{~} instead of spelling out your home directory
in the default pathname in the file-name prompt.
@cindex expansion, tilde
@cindex tilde expansion
@c terminology: tilde substitution vs. tilde expansion (title)
@c bfox: usually =, but sometimes a precedence issue
When a tilde character (@kbd{~}) appears at the beginning of a word
in a command, it is treated as follows:
@table @code
@item ~
@itemx ~/@dots{}
Tilde alone (or followed by a slash) is replaced by the value of the
variable @code{HOME}, or by your home directory if @code{HOME} is unset.
@item ~@var{login-name}
@itemx ~@var{login-name}/@dots{}
Tilde followed by someone's login name is replaced by that person's home
directory.
@item ~+
@itemx ~+/@dots{}
Tilde followed by a plus sign is replaced by the value of the variable
@code{PWD}, which is the directory you are connected to.
(Thus @samp{~+} is the same as @samp{.}.)
@c ? where are ., .. etc covered? Operating system rather than shell?
@item ~-
@itemx ~-/@dots{}
Tilde followed by a minus sign is replaced by the value of the variable
@code{OLDPWD}, which is the directory you were previously connected to.
@end table
@c ? what happens if there is stuff other than / after the ~+ or the ~-
In the following example, I change directories and copy a file
from the first directory to the second:
@example
bash$ cd /top/next/a-subdirectory
bash$ cp ~-/file-to-copy .
bash$
@end example
Note for advanced users:
The above @samp{~} constructs can
also be used in pathnames that are stored in variables.
For example, you can use pathnames
with tildes in the @code{PATH}, @code{MAILPATH}, and @code{CDPATH} variables.
In such variables, any pathname (not just the first) can start with
@samp{~}. That is, @samp{~} can appear after a @samp{:}, which
separates pathnames.
@node History List
@chapter The Command History List
BASH maintains a list of the commands you have given it most recently,
so that you can reuse earlier commands or just review what you did.
This section explains what is actually remembered and how you can
influence that by changing the values of shell variables.
The following sections explain how to make use of the command history.
@xref{Basic Variable Mechanics}, for general information on shell variables.
@cindex history list, size of
@cindex history list, changing size of
The length of the history list is controlled by the @code{HISTSIZE}
shell variable. By default, the value of this
variable is 500; that is, the shell saves the last 500 command lines.
You can make the length of the history list bigger or smaller by
changing the value of the @code{HISTSIZE} variable. A value of zero means
no lines are saved.
In this example, we check the value of @code{HISTSIZE} and find that
it has the default value of 500, then we reduce the value to 128:
@example
bash$ echo $HISTSIZE
500
bash$ HISTSIZE=128
bash$
@end example
The command history does not start out empty whenever you log in.
Rather, commands are saved from session to session. Old commands
are erased from the list only when the length of the list exceeds
@code{HISTSIZE}.
The way BASH remembers commands between sessions is to store them
in a file.
By default, the file is @file{~/.bash_history} in your login directory.
You can change this file name, if you want, by setting the
@code{HISTFILE} variable.
Normally, all commands are remembered in the history list.
You can stop the recording of command lines beginning with a space
or of consecutive identical command lines by setting the
@code{history_control} variable, which is not set by default.
@table @code
@item history_control=ignorespace
stops lines beginning with a space from being recorded.
@item history_control=ignoredups
stops a line identical to the last one in the history list from being recorded.
@end table
@noindent
(Sorry, but there is to way to stop both kinds of command recording at once.)
To see the history list, use the @code{history} command (@pxref{History}).
You could also look at the file in which BASH saves history,
but that is normally updated only when you exit from BASH, so it
will contain the history as of the end of your last session
rather than the current history.
To reuse earlier commands (or portions of earlier commands),
use Emacs-style keystrokes (@pxref{History Use}) or
history substitution (@pxref{History}).
@node Customization, Job Control, File Names, Top
@chapter Customizing Shell Behavior
@cindex customizing shell behavior
@cindex controlling shell behavior
@cindex changing shell behavior
You can control some aspects of the shell's behavior, by changing
values (such as how often the shell checks whether you have new mail)
or by enabling or disabling features (such as whether
@samp{!} invokes history substitution -- if you don't know what that is,
you should probably disable it).
Many parts of this manual include information on how to customize
the behavior being described.
This chapter covers some basic customizations that don't fit naturally
into other topics or that are especially recommended for BASH novices.
@c what to include here?
@c Decision: Only include customization that doesn't fit in another
@c chapter. Customization of particular features will be in those
@c chapters -- e.g. history vars with history stuff
To try out a customization command, you can simply type it
and see if you like the changed behavior.
But you should not waste time retyping your favorite customization
commands each time you log in.
Instead, the commands you always want in effect should be put into a
startup file that BASH automatically executes whenever you log in
(@pxref{Login script}).
@node Variables
@section Shell Variables
@cindex variables, controlling shell behavior
@cindex shell variables, to control behavior
One way to affect shell behavior is to set @dfn{variables} used by the
shell.
@xref{Basic Variables}, for documentation of some of the more basic
variables. Other variables are covered where appropriate throughout
this manual.
@c how should those sections help you manipulate the vars?
@c repeat the how-to info? point to {Variable Mechanics}?
@xref{Shell Vars}, for documentation
of all the variables set or used by the shell.
Some of the mechanics of manipulating shell variables are given here
(@pxref{Basic Variable Mechanics}).
@xref{Variable Mechanics}, for more complete information.
@node Basic Variable Mechanics
@subsection Manipulating Shell Variables
To find out the value of a variable, type @samp{echo $@var{name}}, where
@var{name} is the variable of interest. (Be sure to include the @samp{$}; if
you omit it, @code{echo} just repeats the @var{name} itself.)
To change the value of a variable, type @samp{@var{name}=@var{new-value}},
where @var{name} is the variable you want to change and @var{new-value} is
the new value you want it to have. Don't leave any blank space around the
@kbd{=}.
@emph{Warning:} Be careful to type variable names exactly as they are shown
here, matching uppercase and lowercase letter exactly. If you type a name
wrong before an @samp{=}, you will either change the wrong variable or create
a new variable; if you type a name wrong after @samp{echo $}, you will examine
the wrong variable.
In the following example, we ask for the value of the @code{MAILCHECK}
variable, which is 600, then change it to 0 and verify our change.
@example
bash$ echo $MAILCHECK
600
bash$ MAILCHECK=0
bash$ echo $MAILCHECK
0
bash$
@end example
@node Basic Variables
@subsection Basic Shell Variables
This section documents some basic shell variables whose values you might want
to change. For example, if you use more than one computer, you might want to
change the shell prompt to be the name of the computer you are using instead
of @samp{bash$ }. @xref{Shell Vars}, for documentation of all the variables
set or used by the shell.
@c include any other vars?
@c recommend (point to) other vars? noclobber (for safety)
@heading Directories
@table @code
@item HOME
This holds the default argument for the @code{cd} command. @code{HOME} is set
to your login directory when you log in, so that a simple @samp{cd} command
will return you to your login directory at any time.
For example, I may want to frequently return to the directory where
I work on GNU projects:
@example
bash$ HOME=/usr/jems/gnu
bash$
@end example
@noindent
Now a simple @samp{cd} command will return me to @code{/usr/jems/gnu} instead
of to @code{/usr/jems}.
@item PATH
This is the search path the shell uses when looking for program files
referenced in commands. It holds a sequence of directory names separated by
colons, to be searched from left to right.
For example:
@example
/usr/gnu/bin:/usr/local/bin:.:/usr/ucb:/bin:/usr/bin/X11:/usr/bin
@end example
@c simplify or explain the PATH example
@c :.: is especially opaque
@end table
@heading Mail
@table @code
@item MAILCHECK
This specifies the amount of time that must pass before the shell will check
whether your mail file (the file named by the @code{MAIL} variable) has
changed. The default is 60 seconds (1 minute). An interval of 0 causes the
shell to look for mail before printing each prompt.
For example,
@example
MAILCHECK=600
@end example
@noindent
causes the shell to check for mail before printing a prompt if 600 seconds
have passed since the last check.
@end table
@heading Prompts
@cindex customizing your prompt
@cindex prompt, customizing
When executing interactively, BASH displays the primary prompt (stored in the
variable @code{PS1}) when it is ready to read a command, and the secondary
prompt (stored in the variable @code{PS2}) when it needs more input to
complete a command.
@table @code
@item PS1
This is the primary prompt string. By default it is @samp{bash$ }.
(Actually, the value in PS1 is @samp{bash\$ }, which prints as @samp{bash$ }
unless you are a superuser.)
The following example sets the primary prompt string to be your login name,
followed by an @samp{@@} and the name of the computer, followed by a dollar
sign and a space (for example, @samp{jems@@zurich$ }). The variable value is
enclosed in quotes (either double quotes, as shown here, or single quotes) so
that it can include a space. The special codes @samp{\u} and @samp{\h} for
the user name and host name, as well as other codes useful in prompts, are
explained below.
@c ? apparently \u etc. must be within double quotes, otherwise they are
@c used literally -- 1.06, 2/22/91
@example
PS1="\u@@\h$ "
@c same as "$(whoami)@@$(hostname)$ "
@c better example would be host & directory?
@c single quotes -- deferred eval of $ things till expanded
@c double quotes: $ things eval'ed when ps1 assigned (bfox)
@c should use single if $ things in prompt should change -- e.g. your pwd
@c not relevant to \ methods below, since they're special to prompts,
@c not expanded as more fundamental mechanism
@end example
@item PS2
This is the secondary prompt string, which is printed whenever bash needs more
input to complete a command.
@c what's an example of needing more input? when does it happen?
@c whenever syntax demands more -- e.g. 'if' statement without
@c the closing 'fi'
@c Also, the secondary prompt is printed after some errors. (which?)
By default it is @samp{bash>}.
For example, we can change the secondary prompt string to @samp{more>}:
@example
PS2="more>"
@end example
Note that the secondary prompt, unlike the primary prompt, normally doesn't
end in a space. A space might fool you into thinking the lines of a
multi-line command were automatically separated by a space, whereas they are
actually run together exactly as typed (@pxref{Continuation}).
@end table
The values of @code{PS1} and @code{PS2} can contain special character
sequences beginning with @samp{\} that are decoded as follows. (That is, the
@samp{\} and the following character are replaced by what they stand for when
the prompt is printed.)
@table @code
@item \t
The time.
@item \d
The date.
@item \n
Carriage return and line feed (@sc{CRLF}).
@c notation/terminology: call it newline?
@item \w
The full pathname of the current working directory (the value of the variable
@code{PWD}).
@itemx \W
The last element of the current working directory (the last directory in the
value of the variable @code{PWD}).
@item \u
Your username.
@item \h
Your machine's hostname.
@item \#
The command number of this command (consecutively numbered since login,
starting with 1).
@item \!
The history number of this command (the position of this command in the
history list -- @ref{History List}).
@item \\
A backslash. Since @samp{\} in a prompt normally isn't printed, but rather
gives the next character a special meaning, if you want a @samp{\} in your
prompt you must put @samp{\\} in the prompt string.
@c next is too obscure for ordinary user
@item \s
The name of the shell (the basename of the positional parameter @code{$0}).
@c basename = last element of path name - normally bash
@c $0 is name of prog you're running
@c if execute shell script foo directly (typing name of executable file),
@c inside foo, $0 is foo
@c next is too obscure for ordinary user
@item \$
@samp{$} unless you are the superuser, in which case it is @samp{#}.
@c actual criterion is: if the effective user @sc{id} is 0
@c bfox: when log in, get a non-0 uid: if su to become root, get eff uid=0
@c next is too obscure for ordinary user
@item \@var{nnn}
The character that has the given octal code.
@end table
For example, if for some reason you did
@example
PS1="\d \t\n\u@@\h\n\w \#$ "
@end example
you would have a ridiculously long, multiline prompt, consisting of:
@enumerate
@item
the date and time (separated by a space);
@item
your user name and host name (separated by an @samp{@@});
@item
your working directory, a space, the number of this command
(numbered from 1 since you logged in), a @samp{$}, and a space.
@end enumerate
@example
bash$ PS1="\d \t\n\u@@\h\n\w \#$ "
Sat Feb 9 14:03:58
jems@@zohar
~/gnu 4$ who
jems pty/ttyu0 Feb 9 11:38
gjs pty/ttyu1 Feb 8 15:16
Sat Feb 9 14:04:01
jems@@zohar
~/gnu 4$
@end example
@c following needs explaining -- is this about what happens
@c at prompt-printing time after \'s are processed?
@noindent
Note for advanced users:
After the prompt string is decoded, it is expanded via parameter expansion
and command substitution unless the variable @code{NO_PROMPT_VARS} is set,
@node set
@section The @code{set} Command
You can use the shell's built-in @code{set} command to turn shell options on
and off (@pxref{Built-in}). Here are some option settings you might want to
use:
@c recommend any other features for beginners?
@c 'set -u' (or set -o nounseft...) to make unset vars different from null vars
@c 2/8/91,bfox: 'set -o' is now for options, not history.
@c plain 'set -o' gives list of options
@table @code
@c following set is according to bfox -- must try it
@item set -o histexpand off
disables history substitution (@pxref{History}).
If you don't know what history substitution is, it is a good idea to
disable it.
@end table
@c anything else besides set from builtin chapter? enable?
@node Job Control, Combining commands, Customization, Top
@chapter Background and Foreground Processes
This chapter explains how to run commands in the @dfn{background},
so that you can do more than one thing at a time, and how to
interrupt commands that are running.
First we present a short scenario that illustrates most of
the facilities covered in this chapter. The rest of the chapter
provides full explanations of these facilities.
@c ideas for following scenario:
@c bfox often does:
@c start ftp, c-z it, bg, stops when needs tty input, fg, talk to it
@c find (see other example)
@c **need output lines in following scenario, where marked by **
@example
bash$ monthly-accounting
C-z
bash$ bg
**is job & proc # printed here as for & ?
bash$ make >& log &
[1] 18432
bash$ emacs
@c another good example would be 'mail'
C-z
bash$ jobs
**show both background jobs running & suspended foreground job
bash$ fg
@dots{}
bash$ **a done notice for one of the background jobs
bash$ wait
**done notice for other background job
bash$
@end example
@c bfox: silly to WAIT for 1 job. Should just FG it, and will get
@c prompt when it finishes. Not all systems have job control. (Have
@c backgrounding, but can't interact with the bg job except to send
@c it kill it.) GNU does. But Bash could run on a system V machine,
@c no job control. Wait useful when no job control
@c bfox: can log out & bg jobs keep going!
@c downplay wait -- don't expect users to use it
@c users only need fg, bg, %, auto_resume
@c Fix whole chapter to separate out what have with/without job control
@c INTTERUPT IS NOT THE SAME AS STOP
In this example, we gave the command @samp{monthly-accounting}, which started
our @code{monthly-accounting} program (in the foreground). We didn't want to
sit there waiting for it to finish, so we interrupted it (@kbd{C-z}) and
continued it running (@code{bg}) in the background.
@c Beware: if we didn't have the foresight to redirect output originally
@c it's too late now
We then started a program compilation (@code{make@dots{}}) in the background
(@code{&}). While those background jobs ran, we started up @code{emacs}.
After a while we wanted to see how the background jobs were coming along, so
we interrupted the foreground job (@kbd{C-z}) and asked about our jobs. The
@code{jobs} command reported on our two background jobs and also told us about
our suspended @code{emacs} job. We resumed the @code{emacs} program
(@code{fg}). When we exited from @code{emacs}, BASH reported that our
@code{make} job had finished. We decided to wait for the
@code{monthly-accounting} job to finish also (@code{wait}).
@node Start job
@section Starting a Job
@cindex foreground
Commands such as those shown in most of our examples are run in the
@dfn{foreground}. That is, the command runs and you do not get another BASH
prompt (and the opportunity to run another command) until it finishes. This
is appropriate for short or interactive tasks.
@cindex background
If a program will be running a long time and does not require supervision or
input from the terminal, it may be best run in the @dfn{background}. This
leaves your terminal free for other tasks.
@node Background
@subsection Starting a Background Job
@cindex background processes
@cindex background, placing things in the
@cindex background (&)
@cindex command lines, putting in the background
To run a command in the background, place an ampersand, @samp{&}, at the end
of the command line. For example, the following command runs @code{make}
(which recompiles a program as specified by a data base in the current
directory) in the background (@samp{&}), redirecting @code{make}'s standard
output and error messages to the file @file{log}:
@example
bash$ make >& log &
@end example
@cindex background job's standard input and output
In this example, the command does not read from the standard input, so we had
no reason to redirect standard input. If a background command uses its
standard input, you should normally redirect it, because the command cannot
read from the terminal (which you are using for other things). If a
background task needs input from the standard input and you have not
redirected the standard input:
@c new concept: job control -- what is it? Not defined in this manual
@itemize @bullet
@item
On a system with job control (such as GNU), the background task is suspended
if it needs input from the standard input. You can then bring the task to the
foreground (@pxref{Resuming}) and type the input.
@c add an xref?
@item
On a system without job control (such as @sc{System V}), the background task
is given a null string if it needs input from the standard input.
@end itemize
You should usually redirect the background command's standard output as well
(as shown in the above example), unless you want the output to be interspersed
with your other work on the terminal. If your background task sends output to
the standard output and you did not redirect the standard output, this output
appears on your terminal, @emph{even if you are running another program}.
When you run a background command, the shell prints out its job number and the
@sc{pid} of the last process in the pipeline (@pxref{Numbers}). In the
following example, BASH assigns our background command a job number of 1. It
assigns a @sc{pid} of 18449 to the last process in the pipeline, @samp{wc >
count-file}.
@example
bash$ ls -l | wc > count-file &
[1] 18449
bash$
@end example
@node notify
@subsection Notification of Background Job Termination
@cindex background, the @code{notify} variable
@cindex @code{notify} variable, for background jobs
When a background job is finished, BASH reports its job number, the word
@samp{Done}, and the command line itself:
@example
[1]+ Done ls -l | wc >count-file
@end example
@noindent
@c also reports when a job becomes suspended (by a signal)
Normally the shell reports on jobs only when it issues a prompt, so it doesn't
interrupt what you are doing. If you wish to be told of changes in job status
immediately (not just when you get the next shell prompt), set the
@code{notify} variable, as follows:
@example
bash$ notify=
@end example
@c create a var = set a var; how uncreate it if change your mind?
@node wait
@subsection Waiting for Background Jobs to Terminate
@cindex background, the @code{wait} command
@cindex @code{wait} command
If you want to wait for some or all of your background jobs to finish before
issuing any more commands, you can save yourself the trouble of keeping track
of the termination notices (@pxref{notify}) or repeatedly typing the
@code{jobs} command (@pxref{Jobs command}) by using the @code{wait} command to
wait for the background jobs to finish.
@table @code
@item wait
@itemx wait @var{job_spec}
@c next item added by KELLEM
@itemx wait @var{pid}
The @code{wait} command waits for active background processes to finish. It
suspends operation of your terminal until the specified background job
(@var{job_spec}) or background process (@var{pid}) is finished. If no job or
process is specified, @code{wait} waits for all currently active jobs to
finish.
@c presumably wait finishes immediately if the job is suspended
@var{job_spec} is any job specification
and @var{pid} is a @sc{pid} (@pxref{Numbers}).
Let's assume that you want to start three lengthy jobs running concurrently
and then want to wait for all three jobs to finish before continuing. Here's
how you'd do it:
@c bfox: searches starting with / for files named core
@c & prints to standard out (whole path name)
@example
bash$ find / -name core -print >& core_list &
[1] 2240
bash$ grep "Experience" /home/* >& exper_list &
[2] 2241
bash$ ls -lR / >& dir_list &
[3] 2242
bash$ wait
[1] Done find / -name resume -print >& resume_list
[2]- Done grep "Experience" /home/* >& exper_list
[3]+ Done ls -lR / >& dir_list
bash$
@end example
@noindent
In this example, three long jobs are performed simultaneously: each job is
performed in background by the @code{&} operator at the end of the command.
Notice that each job has its standard output and standard error redirected to
a file with the @code{>&} operator so that the jobs do not write output or
error messages to the screen while they are running in the background. The
@code{wait} command waits for all three commands to finish before allowing
BASH to continue.
@end table
@menu
* Numbers:: Job numbers and process identification
numbers.
* Stopping:: Stopping and suspending jobs.
* Job Specs:: Stopping, restarting, and otherwise
modifying the state of a job.
* fg:: Resuming stopped or suspended jobs.
* bg:: Placing stopped jobs in the background.
* kill:: Terminating Processes.
* nice:: Running processes at a low priority
using the @code{nice} command.
* nohup:: Preventing jobs from stopping using
the @code{nohup} command.
@end menu
@node Numbers, Stopping, Job Control, Job Control
@section Jobs, Processes, and their Identifiers
Each pipeline run by the shell is considered a separate @dfn{job}. (A
pipeline is a set of commands joined by pipes (@pxref{Pipes}), or a command
without pipes -- which can be though of as the simplest possible pipeline,
with only 1 command and 0 pipes.) Each command in the pipeline is run in its
own process (that is, they run simultaneously). Hence a job consists of one
or more processes.
There are a number of commands that act on jobs or processes. (For example,
there are commands to suspend a job or kill a process.) If you give a command
for a job (for example, killing the job), this applies to all the processes in
the job. If you give a command for a process, only that process is affected.
To specify the desired job or process in a command, you may need to refer to
it by number.
@itemize @bullet
@item
Every process has an identifying number, called a @dfn{@sc{pid}} (@sc{p}rocess
@sc{id}entifier). @sc{pid}s, which are assigned by the operating system, are
unique throughout the entire system: No two processes, even belonging to
different users, can have the same @sc{pid} at the same time.
@item
Jobs are identified by small @dfn{job numbers}, which are assigned by BASH.
Unlike @sc{pid}s, these are not unique throughout the system: Any number of
users may have a job 1 at a given time. However, at any moment, all your jobs
have numbers that are different from each other, which is all you need to
uniquely identify them in commands.
@end itemize
When you run a background command, the shell prints out its job number and the
@sc{pid} of the last process in the pipeline (@pxref{Background}). In
addition, you can find out these numbers by using the @code{jobs} command or
the @code{ps} command (@pxref{Jobs command}).
To refer to a process in a command, use its @sc{pid}. To refer to a job in a
command, use a @dfn{job specification} having one of the following forms:
@c Unclear whether to include % as part of job spec.
@c %... can be cmd by self
@c Cmd with job spec as arg may allow omit % if no other arg.
@c (1) job spec starts w %, bt sometimes can leave it out if want to
@c e.g. in fg or bg: fg 4 = fg %4
@c or
@c (2) job spec has no %, sometimes precede with %
@c RMS prefers view (1)
@table @code
@item %@var{number}
refers to the job whose number is @var{number}. For example, @samp{%1} refers
to job number 1.
@c bfox: both %strings require unambiguous match, and look in whole job list
@item %@var{string}
refers to the job whose command line (the command that started the job) starts
with @var{string}. For example, @samp{%emacs} refers to an @code{emacs} job.
If there is more than one job whose name begins with the string, you'll be
given an error message.
@item %?@var{string}
refers to the job whose command line (the command that started the job)
contains @var{string}. For example, @samp{%?mac} may refer to an @code{emacs}
job. If there is more than one job whose name contains the string, you'll be
given an error message.
@item %
@itemx %+
@itemx %%
all refer to the current job (the last job stopped or placed in the
background, @pxref{current job}).
@item %-
refers to the previous job (the second-to-last job stopped or placed in the
background, @pxref{current job}).
@c 1/7/91, 1.06 -- there was only 1 stopped job -- %- got it (same as %+)
@end table
Note that a job specification starts with a @samp{%} character. In certain
contexts, however, where it is clear that a job is being referred to, it is
possible to omit the @samp{%}.
@c I didn't show any examples where could omit it -- e.g. fg cmd
@node Jobs command
@section Finding Out Out What Jobs and Processes You Have
To find out what stopped (suspended) and background jobs you have, you can use
the @code{jobs} command. The following example shows that we have three
suspended jobs.
@c must fix following examples so all based on same set of jobs
@example
bash$ jobs
[1] Stopped rn
[2]- Stopped vi file
[3]+ Stopped emacs file2
bash$
@end example
Use the @code{-l} flag with @code{jobs} to see the jobs' processes as well:
@example
bash$ jobs -l
[1]+ 18448 Done ls -l
18449 | wc >count-file
bash$
@end example
@cindex @code{ps} command
@cindex monitoring active processes
@cindex processes, monitoring
@cindex background, monitoring processes
@c define 'active'?
The @code{ps} command reports more detail about your active processes than
@code{jobs} does, but it treats the processes as individuals and doesn't group
them into jobs. When typed without options, @code{ps} gives you the following
information. (Note that @code{ps} is not built into BASH, so its output is
different from system to system; however, the basics remain the same.)
@table @code
@item PID
The process identification number.
@item TTY
The terminal from which the process was started.
@item TIME
The amount of computer time the process has used so far.
@item COMMAND
The name of the process.
@end table
Here's an example of the output of @code{ps}:
@example
bash$ jobs
[1]+ Stopped emacs
bash$ ps
PID TTY TIME COMMAND
2249 ttyp0 0:00 ps
2184 ttyp0 0:00 emacs
2170 ttyp0 0:00 bash
bash$
@end example
@noindent
This @code{ps} command shows that we have three processes: the @code{ps}
process itself, an @code{emacs} process (which we presumably suspended
earlier), and the @code{bash} process itself. (@code{ps}, unlike @code{jobs},
reports on foreground as well as background processes.) BASH has assigned job
number 1 and process number 2184 to @code{emacs}.
@xref{ps, , @code{ps}, utilities, The GNU Utilities Manual},
for more information.
@node current job
@subsection Current Job and Previous Job
The @samp{+} and @samp{-} in the output of @code{jobs} identify the ``current
job'' and ``previous job'' respectively. The job most recently stopped
(suspended) or put in the background is called the @dfn{current job}.
@c last sentence unclear
@c In particular, why is a Done job marked + ? bfox: May fix later
@c Current job concept is useless for it, since you can't act on it
@c Remains + until it's reported to you and removed from list
It is marked with a plus sign, @samp{+}, in the jobs listing. The
second-to-last job stopped or put in the background is called the
@dfn{previous job}. It is marked with a minus sign, @samp{-}, in the jobs
listing. When the current job is terminates or is moved to the foreground,
the previous job becomes the new current job.
The concept of ``current job'' is used for defaulting arguments
to the @code{fg} and @code{bg} commands (@pxref{Resuming}).
@c need examples
@node Stopping, Job Specs, Numbers, Job Control
@section Interrupting a Job
@c How kill a stopped job?
@c bfox: kill job-spec (shell continues & signals the process -- you
@c don't have to continue it yourself)
@c Shell tells op sys start process, processes can communicate by signals
@c Kill exists as ordinary disk-file cmd
@c Shell has separate built-in kill cmd so can do jobs, which are
@c shell (not op sys) concept.
@c If program doesn't disable TERM, it will definitely kill you
@c rms: program handles signal if wants, otherwise unix does it
@c kill -9 (9=SIGKILL) is signal no one can ask to handle, thus kills anything
@c confusion in this section between Job, Process, Program
@c confused terminology: stop, kill, suspend
@c rms: stop=suspend, terminate=kill (gone)
@node Interrupt foreground
@subsection Interrupting the Foreground Job
@cindex stopping jobs
@cindex jobs, stopping
@cindex suspending jobs
@cindex jobs, suspending
You may want to abort the program you are currently running (in the
foreground), or you may want to interrupt it temporarily in order to do
something else.
The following keys stop the foreground job, placing it in a type of
``suspended animation'' so that it can be resumed if desired
(@pxref{Resuming}).
@c none of these interrupts worked while running vi under bash
@c rms: interactive editors turn things off
@table @code
@item @kbd{C-z}
This stops (suspends) the foreground job immediately.
@c but SIGTSTP says programs may ignore C-z? (bfox: can ignore if enabled)
@item @kbd{C-y}
This is similar to @kbd{C-z} except it causes the process to be stopped
(suspended) only when that process attempts to read input from the terminal.
@c KELLEM: note that C-y (by default in readline lib) is bound to `yank'
@c thus fine when readline not running
@c bfox: normally type C-y ahead of time (if at prompt, you would type C-z)
@c op sys buffers it & prepares to send signal later
@c same true of C-z (op sys cmd, not bash)
@end table
@noindent
Note for advanced users:
@kbd{C-z} and @kbd{C-y} will not suspend the shell itself.
@c Does this belong here? There's lots of other stuff it won't suspend, too.
To suspend a shell, such as one started with the @code{su} command,
use the @code{suspend} command (@pxref{Built-in}).
The following keys kill the foreground job.
The job cannot be resumed.
@table @code
@item @kbd{C-c}
This kills the foreground job immediately.
@item @kbd{C-\}
This kills the foreground job immediately and it is much harsher than @kbd{C-c}.
@c harsher in what way - just core dump? is core dump the purpose of C-\ ?
@c bfox: C-c is SIGINT, which usually kills
@c but C-\ is SIGKILL, which can't be ignored
This method usually produces a core (memory) dump for later analysis.
@c why 'usually'? bfox: core dump happens if not disabled with ulimit
@c by setting core dump size to 0
@c He normally has dumps disabled, enables to reproduce a bug
@c rms: if program handles signal, it may not produce dump -- otherwise produced
@c what is the core dump useful for? rms: debugging
@end table
All of the above keystrokes can be reassigned to other keys,
by using @code{stty}.
@c need ref for stty
We are just covering the most common keyboard methods of stopping jobs.
Your operating system manual will tell you about other
keyboard interrupts and how to remap your keyboard.
No matter which method you use (except @kbd{C-c}), the shell tells you
when your program, or job, has been ``Stopped'', and prints another prompt.
@c really does it for C-\ but not C-c ?
@c be clearer what shell tells you
@node kill, nice, bg, Job Control
@subsection Interrupting a Background Job
@cindex stopping jobs
@cindex jobs, stopping
@cindex suspending jobs
@cindex jobs, suspending
@cindex background, stopping jobs
@cindex background, suspending jobs
@cindex background, terminating processes
@cindex processes, terminating
@cindex terminating processes or jobs
You cannot use the keyboard interrupts (@pxref{Interrupt foreground})
to interrupt a background job, since background jobs do not listen to
the terminal.
To suspend or terminate a background job, you can do either of the following:
@itemize @bullet
@item
Use the @code{kill} command (described below).
@item
Move the job to the foreground (@pxref{fg<>bg}) then use one of the
keyboard interrupts for foreground jobs (@pxref{Interrupt foreground}).
@end itemize
@cindex @code{kill} command
@cindex background, the kill command and
@cindex jobs, the kill command and
@cindex signals, for the @code{kill} command
@c new concept: signal
@table @code
@item kill @r{[}-@var{sigspec}@r{]} @var{pid}
@itemx kill @r{[}-@var{sigspec}@r{]} @var{job_spec}
Send the process identified by @var{pid} or all processes in the
job identified by @var{job_spec}
the terminate signal,
@c SIGTERM
or the signal specified by @var{sigspec}, if given.
@var{pid} is a process identification number and
@var{job_spec} is a job specification (@pxref{Numbers}).
Signals are specified either by number or by name, as explained below.
@c where are the numbers defined? document here? (appendix)
@item kill -l
This lists all the possible signal names (and numbers).
It does not affect any jobs or processes.
@end table
Here's a summary of the most common and useful signals.
In the @code{kill} command, you can use any of the following:
@itemize @bullet
@item
the name shown -- e.g. @code{SIGKILL}
@item
the part of the name after @samp{SIG} -- e.g. @code{KILL}
@item
the lowercase version of the part of the name after @samp{SIG} -- e.g.
@code{kill}
@end itemize
@c compare to appendix -- don't want same table in both places
@table @code
@item SIGHUP
This is a gentle signal you can send to processes that you want to
kill when you want to allow them to clean up after themselves (for
example, delete temporary files, kill subprocesses, etc.). It is a
good practice to try to kill jobs with this signal first, before trying
any of the harsher signals. Some programs see this signal as a request
for them to re-initialize some internal state or re-read a startup file,
so this signal is not always used strictly for killing a process.
@item SIGINT
This is the signal generated (normally) by @kbd{C-c} on the keyboard.
This signal will kill most processes, although a program may choose to
ignore @code{SIGINT}. @code{SIGINT} also allows a process to clean up
after itself before dying.
@c how differs from SIGHUP? rms: SIGHUP means terminal is disconnected.
@c prog might die from hup but not c-c
@item SIGQUIT
This is the signal generated (normally) by @kbd{C-\} on the keyboard.
@c normally = if not remapped
@code{SIGQUIT} is identical to @code{SIGINT} except that it requests that the
operating system produce a diagnostics file called a @dfn{core dump},
which is placed into a file named @file{core}.
This can be useful for debugging.
@item SIGTERM
@code{SIGTERM} is similar to @code{SIGINT} except that it is normally produced by a
program and not from the @kbd{C-c} on the keyboard. Note that
some programs treat @code{SIGTERM} differently from @code{SIGINT}.
@item SIGKILL
@code{SIGKILL} is the harshest ``kill'' signal. It kills a process
without warning
and without allowing the process to clean up after
itself.
@c rms: i.e. doesn't signal process, just kills it
@code{SIGKILL} should be used as a last resort, if
@code{SIGHUP}, @code{SIGTERM}, @code{SIGINT}, and @code{SIGQUIT} don't
work.
@item SIGTSTP
@code{SIGTSTP} is the signal sent (normally) by the @kbd{C-z} key on the
keyboard.
@c normally = modulo remapping
Some programs may ignore this signal. This signal does not
kill the process but instead @emph{stops} the process, putting the
program into a suspended state.
@item SIGSTOP
@code{SIGSTOP} is identical to @code{SIGTSTP} except it is not generated from
the keyboard by @kbd{C-z}; it is must be sent with @code{kill} or from within
a program.
@item SIGCONT
@code{SIGCONT} causes a @emph{stopped} process to continue running. A stopped
process is sent this signal by BASH when the @code{fg} and @code{bg}
commands are used.
@end table
The following example terminates a @code{tip} process that has
been stopped earlier:
@c tip is for: communicate over serial port to log into another machine
@c replace example -- don't use tip or HUP (HUP normally due to hangup, not sent by you)
@c rms: normally do kill, or kill -stop, or kill -kill
@c bfox: either kind of name can be lower case
@c replace example
@example
bash$ jobs -l
[1]+ 29854 Stopped tip
bash$ kill -HUP 29854
[1]+ Hangup tip
bash$ jobs
bash$
@end example
@noindent
For a @code{tip} process, it is especially useful to use the @code{-HUP}
signal so that @code{tip} cleans up the @sc{UUCP} lock files that it leaves
around.
@node Stopped jobs
@subsection Logging Out With Stopped Jobs
@cindex logging off, with stopped jobs
@cindex jobs, logging off with stopped
@cindex stopped jobs, logging off with
If you have stopped jobs that you have forgotten about and you try to
log off, you will be given a warning that you have ``Stopped jobs'' and
will not be allowed to log off. If you continue to try to log off, you
will eventually be successful, but the operating system will kill
(terminate) all your stopped jobs.
@c what if you have running (background) jobs?
@c ? bfox: they just keep silently running ?
@c csh sends hup to children when logs up, bash currently doesn't
@c might change it -- if so, add nohup biltin
It is much better to bring the stopped jobs to the foreground
(@pxref{Resuming}) and terminate them properly, so that can clean up
after themselves (save files, etc.).
You can also prevent jobs from being killed
when you log off by using the @code{nohup} command (@pxref{nohup}).
@node Resuming
@section Resuming a Suspended Job
A job that has been suspended (@pxref{Stopping}) can be resumed.
That is, you can make it continue from where it left off.
The resumed job can be run either in the foreground or in the
background, regardless of whether it was foreground or background
when it was interrupted.
The following methods of resuming jobs are described more fully below:
@itemize @bullet
@item
To resume a suspended job in the foreground, use the @code{fg} command
or just type a job specification (@pxref{Numbers}).
@item
If you set the @code{auto_resume} variable, typing a command
may resume a suspended job instead of starting a new one.
@item
To resume a suspended job in the background, use the @code{bg} command
or just type a job specification (@pxref{Numbers}) followed by an
ampersand (@samp{&}).@refill
@end itemize
@table @code
@item fg
@itemx fg @var{job_spec}
@itemx @var{job_spec}
Bring the specified job into the foreground, and resume running it. If
@var{job_spec} isn't specified, @code{fg} acts on the current job
(@code{%}).
The following example resumes the current job in the foreground:
@example
bash$ fg
@end example
The following example resumes a stopped @code{du} process in the foreground:
@example
bash$ %du
@end example
@item bg
@itemx bg @var{job_spec}
@itemx @var{job_spec} &
Place the specified job in the background, and resume running it as if
it had been started with @samp{&}. If @var{job_spec} is omitted,
@code{bg} acts on the current job (@code{%}).@refill
@example
bash$ find / -name resume -print >& resume_list
C-z
[1]+ Stopped find / -name resume -print >& resume_list
bash$ bg
find / -name resume -print >& resume_list &
bash$
@end example
@noindent
Here we started the @code{find} command in the foreground but then
stopped it (with @kbd{C-z}) and placed it in the background when we got
tired of waiting for the command to finish.
The following example places job 2 in the background:
@example
bash$ jobs
[1]- Stopped find / -name resume -print >& resume_list
[2]+ Stopped ls -R / >& dir_list
bash$ %2 &
ls -R / >& dir_list &
bash$
@end example
@c 12/90, bash 1.06.25: bug: 'exact' has no effect - never need whole name
@item auto_resume=
@itemx auto_resume=exact
If you create the @code{auto_resume} variable (e.g. by typing
@samp{auto_resume=}), then if you type a command that matches
a suspended job's command,
@c match of cmd word
@c bfox: auto_resume is for 1-word commands
@c must be 'simple word' -- e.g. \emacs is new
@c bfox: to specifically talk about 1st wd of cmd, call it ``command word''
the suspended job is resumed instead of a new job being started.
If the value of @code{auto_resume} is @code{exact}
(you set @samp{auto_resume=exact}), then you must
type the entire job name; if the value is anything else,
then only part of job name is enough to resume it.
@c fix: job name = command word
If there is more than one job
with such a name, the job with the highest number is resumed.
For example, assume that you have a stopped Emacs job:
@example
bash$ jobs
[1]+ Stopped emacs -f rmail
@end example
@itemize @bullet
@item
If you have not set @code{auto_resume}, then the command
@example
bash$ emacs
@end example
@noindent
will start another Emacs job, and the old job will remain suspended.
@item
If you have set @code{auto_resume}, the above @samp{emacs} command
will resume the stopped Emacs job.
@item
If you have set @code{auto_resume} to anything but @code{exact}, an
abbreviated command (such as @samp{ema}) will also resume the stopped
Emacs job.
@end itemize
@end table
@node fg<>bg
@section Moving a Job Between Foreground and Background
To move the job that is running in the foreground to the background,
suspend the job (@pxref{Stopping})
and then resume it in the background (@pxref{Resuming}).
To make a job that is running in the background be the foreground job,
pretend the job has been suspended (though there is no need to
actually suspend it) and ``resume'' it using any method of resuming jobs
in the foreground (@pxref{Resuming}).
@c BFOX: Flush NICE from manual
@c KELLEM: nice is NOT a builtin -- description below looks like it's from csh
@c /bin/nice usage is typically: nice [-number] command (both BSD and SysV)
@c note the `-' before number .. what's GNU nice going to do?
@c rms: may be in posix 2 or 2a
@ignore
@node nice, nohup, kill, Job Control
@section Running Processes at a Low Priority Using @code{nice}
@cindex jobs, the @code{nice} command
@cindex background, the @code{nice} command
@cindex @code{nice} command, for lower priority
@cindex jobs, running at low priority
@cindex background, running processes at a low priority
The @code{nice} command causes a background process to be run at a
low priority. The operating system runs any commands specified by
@code{nice} when the machine has nothing else to do (it runs those
commands less often than normal). This way, commands that normally
consume large amounts of system resources, slowing the system
considerably, are run in stages that don't slow the system down quite
as much. Of course, a program that is run at a lower priority takes
longer to finish, but it doesn't interfere with more important
programs, either.
The format of the @code{nice} command is:
@example
nice @r{[}@var{number}@r{]} @var{command-line}
@end example
@noindent
where @var{command-line} is the command line you want to place at a
lower priority.
If present, the @samp{@var{number}} option causes @code{nice} to
increment the priority by the amount given, up to a limit of 20. The
higher the value given, the lower the command's scheduled priority.
The default value for @var{number} is 10.@refill
@c need example: maybe 'nice make -k hairy-program >& log' (rms)
@menu
* exception:: Using @code{nice} to force processes to run
at a higher priority than normal.
@end menu
@cindex @code{nice} command, using for higher priority
@c what's a super-user? = root
Note for advanced users:
The super-user may give commands a higher priority than normal by using
a negative @var{number}, for example @samp{-5}.
@end ignore
@c comments by KELLEM
@c should `nohup' description be here? machine specific
@c maybe should just note that way nohup works is machine dependent
@node nohup, , nice, Job Control
@section Preventing Jobs From Stopping Using @code{nohup}
@c ? stop = be killed = be terminated?
The @code{nohup} command prevents commands from stopping, or being
killed, when you log out.
Normally when you log off your system, any
commands or processes that are running in the background are
terminated.
@c ? aren't suspended processes terminated too?
@c what happens if you suspend a process started with nohup, then resume
@c it? is it still nohup?
The @code{nohup} command prevents hangup signals
(@code{SIGHUP}, normally generated when you log off),
interrupt signals (@code{SIGINT}, normally generated by @kbd{C-c}),
and quit signals (@code{SIGQUIT}, normally generated by @kbd{C-\})
from terminating your program.@refill
@c ? any other signals disabled?
@cindex @code{nohup} command
@cindex jobs, the nohup command
@cindex background, the nohup command
@cindex preventing job suspension/stopping when logging out
@cindex logging out, preventing job suspension/stopping
The format of the @code{nohup} command is:
@example
nohup @var{command-line}
@end example
@noindent
where @var{command-line} is the command you don't want interrupted.
Any output the @var{command-line} produces is
put into a file called @file{nohup.out} in your current directory.
@c ? i.e. output to standard output?
(If this file cannot be written to your current directory, @code{nohup}
places it in your home directory.)
@c ?
THIS DESCRIPTION IS MACHINE SPECIFIC, UNLESS WE HAVE A GNU NOHUP (bfox).
@c i.e. nohup may not change priority
@c point of nohup: keep running after hang up
The @code{nohup} command increments the priority by 5.
(@xref{nice}, for an explanation of priority.). Make sure that you
invoke @code{nohup} from the shell prompt with @samp{&}, so that it
won't respond to interrupt signals, or take input from the next user.
@c format above should thus show with & ?
@c ? if it's not given with &, how can you log out?
@c what next user?
@c rms: it still has association with tty#, might respond to c-c etc.
@node Combining commands, Editing, Job Control, Top
@chapter Combining Several Commands on One Line
@node Sequential cmds, Parallel cmds, Combining commands, Combining commands
@section Sequential Commands
There are several ways to type several commands in one command line,
such that the commands are executed one after another.
You can either make the sequence execute unconditionally,
as if you had typed the commands one after another at the shell prompt;
or you can make execution of the sequence stop early depending
on the outcome of one of the commands, as if you had typed the commands
one at a time and decided whether to continue as you went along.
To do this, give a command of the form
@example
@var{command} @r{[}@var{separator} @var{command}@r{]}
@end example
That is, give any number of commands with an appropriate separator
between each pair, as defined in the following:
@table @code
@item ;
allows you to put
several commands on the same line, to be executed sequentially.
Separate each command from the next with a semicolon, @samp{;}.
@cindex @code{;}, sequential command sequence
No command in the sequence is executed until you end the line (press
@key{RET}).
Then the commands are executed in order, from left to right,
as if you had typed each separately and waited for it to finish
before typing the next.
@cindex separating commands
@cindex command line, separating commands on a
For example:
@example
bash$ cp test test-old; du > test; ls -l test*
@end example
@item &&
indicates conditional execution of commands in the sequence.
@samp{&&} means @sc{and}; the trailing commands are executed only if the
preceding commands are executed successfully.@refill
@cindex @code{&&}, conditional command sequence
@cindex joining commands
@cindex commands, joining
@cindex pipelines, joining
@cindex pipelines, conditional execution of
@cindex commands, conditional execution of
For example, if there is no file named @file{garbage.test},
then an attempt to list directory information for such a file
(@samp{ls -l@dots{}}) and an attempt to view its contents (@samp{cat@dots{}})
will both fail:
@example
bash$ ls -l garbage.test ; cat garbage.test
garbage.test not found
cat: cannot open garbage.test
bash$
@end example
But if @samp{&&} instead of @samp{;} joins the two commands,
the second command is performed only if the
first command is successful. Since the file @file{garbage.test} doesn't exist,
we get the error message associated with @code{ls} and @code{cat} isn't run:
@example
bash$ ls -l garbage.test && cat garbage.test
garbage.test not found
bash$
@end example
@item ||
indicates conditional execution of commands in the sequence.
@samp{||} means @sc{or}; the remaining commands are executed only if the
preceding commands are @emph{not} executed successfully.@refill
@cindex @code{||}, conditional command sequence
@cindex joining commands
@cindex commands, joining
@cindex pipelines, joining
@cindex pipelines, conditional execution of
@cindex commands, conditional execution of
For example:
@example
bash$ cat garbage.test || cat junk.test
cat: cannot open garbage.test
This is the contents of junk.test.
@end example
@noindent
The first @code{cat} failed to find @file{garbage.test}, so the second
@code{cat} was performed.
@end table
@node Parallel cmds, Combination precedence, Sequential cmds, Combining commands
@section Simultaneous Commands
There are two ways to type several commands in one command line,
such that the commands are executed simultaneously, in separate
processes.
You can specify either independent commands or commands whose
inputs and outputs are linked together.
To do this, give a command of the form
@example
@var{command} @r{[}@var{separator} @var{command}@r{]}
@end example
That is, give any number of commands with an appropriate separator
between each pair, as defined in the following:
@table @code
@item |
joins commands together into a pipeline.
The standard output of each command is redirected (connected) to the
standard input of the next command in the sequence.
@xref{Pipes}.
@item &
causes each command to run in the background.
The commands are executed simultaneously in the background,
as if you had typed each one separately, terminated with @kbd{&}.
@xref{Job Control}.
Note: @samp{&} actually terminates commands rather than separating
them. This is a difference from the other command combiners in
this chapter. Thus be sure to put a @samp{&} after the last command
as well as between commands, or the last command will @emph{not} run
in the background.
@end table
@node Combination precedence, , Parallel cmds, Combining commands
@section Mixtures of Sequential and Simultaneous Commands
Any or all of the command separators described in this chapter
(@samp{;}, @samp{&&}, @samp{||}, @samp{|}, @samp{&})
can be used in a single command.
The order of precedence (from highest to lowest) is
@table @code
@item |
pipeline
@item && @r{and} ||
``and'' and ``or'', equal precedence, processed from left to right
@item ; @r{and} &
sequential and background, equal precedence, processed from left to right
@end table
However, if you have a mixture of operators, you should usually group
the subcommands with parentheses or braces (@pxref{Grouping}), rather
than assume you know how the command will be interpreted.
@c rms: for mixtures of operators, tell them to group with ()
@node Editing, History, Combining commands, Top
@chapter Command Line Editing
@menu
* Readline Intro:: An introduction to editing command lines
using @code{readline}.
* Syntax:: The basic editing commands.
* Customizing:: Customizing @code{readline} to use other
key bindings. Includes a complete list of
all commands used in editing.
* vi mode:: Editing using other modes, including a
@code{vi} editing mode.
@end menu
@cindex @code{readline} library
@cindex command lines, editing
@cindex editing command lines
@cindex Emacs, command lines and
BASH provides powerful facilities for editing the command line
you are currently typing, so as to minimize the amount of typing
needed to fix mistakes.
It also includes facilities to save typing by giving you access to
earlier commands and by completing things (such as file names) that you have
not finished typing.
The command-entry features described here are not specially programmed
into BASH.
Rather, they are provided by the @code{readline} library, which is used by a
number of other GNU programs besides BASH.
This means that you can use the same typing and editing facilities
with a variety of programs.
By default, @code{readline} has Emacs-like key bindings.
That is, most features that Emacs also has (such as moving the cursor
over words or characters) are invoked by the same keystrokes as
in Emacs.
@xref{Customizing Readline}, for how to change any key bindings you
don't like and customize other aspects of @code{readline}'s behavior.
@menu
* Movement:: Moving about the line.
* History Commands:: Using previous lines.
* Text:: Commands for changing text.
* Buffer:: Commands for killing and yanking.
* Numeric Arguments:: Specifying numeric arguments and
repeat counts.
* Completion:: Getting @code{readline} to do the
typing for you.
* Miscellaneous:: Other miscellaneous commands.
@end menu
@node Readline Commands
@section @code{readline} Commands
The following sections list all the functions provided by @code{readline}.
Each entry consists of
@itemize @bullet
@item the function name
You do not need the function name unless you want to change the key
binding (@pxref{Customizing Readline}).
@item the default key binding (in parentheses)
This is the key you press to invoke the function.
If no key binding is shown, then you can't use the function
unless you bind it to a key (@pxref{Customizing Readline}).
@item a short description of what the function does
@end itemize
@cindex command editing, advanced
@cindex editing commands, advanced
@cindex @code{readline} editing commands, advanced
@node Movement, History Commands, Customizing, Customizing
@subsection Moving the Cursor
Here are the @code{readline} cursor movement commands:
@cindex @code{readline} library, cursor movement commands
@cindex cursor movement commands in the @code{readline} library
@table @asis
@item beginning-of-line (@kbd{C-a})
Move to the start of the current line.
@item end-of-line (@kbd{C-e})
Move to the end of the line.
@item forward-char (@kbd{C-f})
Move forward (right) one character.
@item backward-char (@kbd{C-b})
Move backward (left) one character.
@item forward-word (@kbd{M-f})
Move forward (right) one word.
@item backward-word (@kbd{M-b})
Move backward (left) one word.
@end table
@node Text, Buffer, History Commands, Customizing
@subsection Changing the Command Text
@c new term: 'cursor point'
@c numeric &/or negative args mentioned but never explained
@cindex @code{readline} library, commands to change text
@cindex changing text commands in the @code{readline} library
Here are the @code{readline} commands for text manipulation:
@table @asis
@item quoted-insert (@kbd{C-q}, @kbd{C-v})
Add the next character that you type to the line verbatim. This allows
you to insert a control character, for example,
and not have it act as an editing key.
For example, if you want to search for a @kbd{C-l} in a file,
you can type the @kbd{C-l} argument to the @code{grep} command
by typing @kbd{C-q C-l}.
@item tab-insert (@kbd{M-TAB})
Insert a tab character.
(A @kbd{TAB} character itself normally invokes completion
rather than being inserted into the command line -- @pxref{Completion}.)
@item self-insert (a, b, A, 1, !, ...)
Insert the typed characters verbatim.
All printing characters except @kbd{TAB} and newline
@c ? @kbd{RET} ?
(i.e., all non-control, non-meta characters)
@c source: bfox
are inserted as typed.
@item transpose-chars (@kbd{C-t})
Interchange the character before the cursor with the character
at the cursor and position the cursor after both characters. If the
cursor point is at the end of the line, then transpose the two
characters before the cursor point. Negative arguments are invalid.
@item transpose-words (@kbd{M-t})
Interchange the word before the cursor with the word
at the cursor and position the cursor after both words.
@item upcase-word (@kbd{M-u})
Change the current (or following) word to uppercase and put the cursor
after the word. When given with a
negative argument, the previous word is changed to uppercase, but the
cursor point is not moved.
@item downcase-word (@kbd{M-l})
Change the current (or following) word to lowercase and put the cursor
after the word. When given with a
negative argument, the previous word is changed to lowercase, but the
cursor point is not moved.
@item capitalize-word (@kbd{M-c})
Capitalize the current (or following) word and put the cursor
after the word. When given with a negative
argument, the previous word is capitalized, but the cursor point is not
moved.
@end table
@node Buffer, Numeric Arguments, Text, Customizing
@subsection Deleting and Restoring Text
@cindex readline library, killing commands
@cindex killing commands in the readline library
@cindex readline library, yanking commands
@cindex yanking commands in the readline library
@cindex readline library, buffer commands
@cindex buffer commands in the readline library
Here are the @code{readline} commands involved in deleting text and
restoring previously deleted text.
In the following table, the term @dfn{kill} means to delete text from a
line, but save that text in a buffer for later retrieval.
Usually you retrieve killed text by @dfn{yanking} it back into the
line. The term @dfn{yank} means to retrieve text from a buffer and
insert it at the cursor in the current line.
Text that is @dfn{deleted} rather than killed is not saved and
cannot be yanked back.
@table @asis
@item delete-char (@kbd{C-d})
Delete the character under the cursor.
Note: If the cursor is at the
beginning of the line, there are no characters in the line, and the
last character typed was not @kbd{C-d}, then @kbd{C-d} means
end-of-file return @sc{eof}, and BASH exits.
@c bfox: bash exits (logs you out)!! ignoreeof can protect you from this
@item backward-delete-char (@key{DEL})
Delete the character behind the cursor. A numeric argument given with
this command causes the characters to be killed instead of deleted.
@item kill-word (@kbd{M-d})
Kill the text from the current cursor position to the end of the
current word or, if between words, to the end of the next word.
@item backward-kill-word (@kbd{M-DEL})
Kill the text from the current cursor position to the start of the
current word or, if between words, to the start of the previous word.
@c bfox: words delimited by
@c when doing completion space tab nl " \ ` ' @ $ > < =
@c in word movement/deletion non-alphanumeric
@item kill-line (@kbd{C-k})
Kill the text from the current cursor position to the end of the line.
@item backward-kill-line ()
Kill backward to the beginning of the line. That is, kill the text from
the beginning of the line to the current cursor position. This is
normally not bound to a key. (See @code{unix-line-discard}, which is bound to
@kbd{C-u}.)
@item unix-line-discard (@kbd{C-u})
Kill backward to the beginning of the line.
This is identical to backward-kill-line.
@item unix-word-rubout (@kbd{C-w})
Kill the text from the current cursor position to the previous
whitespace. This is different from @kbd{M-DEL} because the word
boundaries are different.
@item yank (@kbd{C-y})
Restore the most recently killed text back into the line at the cursor.
@item yank-pop (@kbd{M-y})
Restore the next to most recently killed text back into the line at the
cursor. You can do this only if the prior command was @kbd{C-y} or
@kbd{M-y}.
@end table
@node History Commands, Text, Movement, Customizing
@subsection Manipulating the Command History
@cindex readline library, history commands
@cindex history commands in the readline library
Here are the @code{readline} commands for manipulating the
command history (@pxref{History List}).
@table @asis
@item accept-line (@key{RET}, newline character)
Accept the line regardless of where the cursor is. If this line is not
empty, add it to the history list. If this line was a history line,
then restore the history line to its original state.
@c bfox: editing a cmd line retrieved from history
@c if execute it, becomes new history line
@c if edit it but move back to new line, old line stays edited, marked
@c with * in history list -- can undo to restore it
@item previous-history (@kbd{C-p})
Move up through the history list.
@item next-history (@kbd{C-n})
Move down through the history list.
@item beginning-of-history (@kbd{M-<})
Move to the oldest line in the history list.
@item end-of-history (@kbd{M->})
Move to the most recent line in the history list.
@c must explain searches -- how to abort, when it's executed (RET), etc.
@c How get the found line for editing?
@c string is inside `', cursor at matching spot, RET executes, or just
@c start editing it -- it becomes current command
@item reverse-search-history (@kbd{C-r})
Search backward starting at the current line and moving up through the
history as necessary. This is an incremental search.
@item forward-search-history (@kbd{C-s})
Search forward starting at the current line and moving down through the
the history. This is an incremental search.
@end table
@node Numeric Arguments, Completion, Buffer, Customizing
@subsection Specifying Numeric Arguments
@cindex readline library, specifying numeric arguments
@cindex numeric arguments, specifying in the readline library
Here is how you specify numeric arguments in @code{readline}:
@c explain what args are for, where can use them
@table @asis
@item digit-argument (@kbd{M-0}, @kbd{M-1}, ... @kbd{M--})
Add this digit to the argument already accumulating, or start a new
argument. @kbd{M--} (meta-minus) starts a negative argument.
@item universal-argument ()
This lets you type numeric argument digits without metafying.
To start a negative argument use the minus key.
@c use minus when? after the ^U (or whatever bound to)
A minus sign alone, with no other digits following, means @minus{}1.
This is normally not bound to a key.
Assume you have bound @kbd{C-u} to universal-argument. Then
@kbd{C-u} followed by a character that is neither a digit nor a minus
sign means ``multiply the next argument by 4''. @kbd{C-u C-u} means
multiply the next argument by 16.
@c possible to reword without mentioning C-u ?
@c probably not, if unbound commands are inaccessible
@end table
@node Completion, Miscellaneous, Numeric Arguments, Customizing
@subsection Completion: Letting @code{readline} Type For You
@cindex readline library, completion commands
@cindex readline library, shortcut commands
@cindex completion commands in the readline library
@cindex shortcut commands in the readline library
You can save typing by asking for completion of the word you are in the
midst of typing. The system can complete partially-typed file names,
command names, variable names, user names, and host names. You can
either specify the type of completion you would like to perform on the
text before the cursor, or you can let the system guess what kind of
name is being typed and complete it accordingly.
@table @asis
@item complete (@key{TAB})
Try to complete the text before the cursor
In particular,
@c source: bfox
@itemize @bullet
@item variable
If the word before the cursor starts with @samp{$},
try to complete it as a variable name.
@item user
If the word before the cursor starts with @samp{~},
try to complete it as a user name.
@item host
If the word before the cursor starts with @samp{@@},
try to complete it as a host name.
@item command
If the word before the cursor is the first word in
the command line, try to complete it as a command name.
@c e.g. ema<TAB>-->emacs
@item file
If none of the above cases apply,
try to complete the word before the cursor as a file name.
@end itemize
@item possible-completions (@kbd{M-?})
List the possible completions of the text before the cursor.
See above for what kind of completion is assumed.
@c JEMS: tested 1/7/91 -- not all worked (bfox says fixed)
@item complete-variable (@kbd{M-$})
@itemx possible-variable-completions (@kbd{C-x $})
@itemx complete-username (@kbd{M-~})
@itemx possible-username-completions (@kbd{C-x ~})
@itemx complete-hostname (@kbd{M-@@})
@itemx possible-hostname-completions (@kbd{C-x @@})
@itemx complete-command (@kbd{M-!})
@itemx possible-command-completions (@kbd{C-x !})
@itemx complete-filename (@kbd{M-/})
@itemx possible-filename-completions (@kbd{C-x /})
@c rewrite
Each of these specify the type of completion you would like to perform
on the text before the cursor, whether it be filename, username,
hostname, variable name, or hostname completion, respectively. These
BASH-specific @code{readline} commands do not depend on a prefix
character; though, if one is there, such as the dollar sign, @samp{$},
at the beginning of variable names, the commands will still work.@refill
The @code{possible-@dots{}-completions} commands are similar in
functionality to the @code{possible-completions} command.
Note that the specific completion commands are specific to BASH and are
@emph{not} defined in the @code{readline} library.
@end table
@node Miscellaneous, , Completion, Customizing
@subsection Some Miscellaneous Commands
@cindex readline library, miscellaneous commands
@cindex miscellaneous commands in the readline library
@table @asis
@item clear-screen (@kbd{C-l})
Clear the screen, leaving the current line at the top of the screen.
@item abort (@kbd{C-g})
Sounds the warning bell and stops whatever was happening when you typed
these keystrokes.
For example, @kbd{C-g} can be used to abort entry of a numeric
argument (@pxref{Numeric Arguments}) or a search through command
history (@pxref{History Commands}).
@item do-uppercase-version (@kbd{M-a}, @kbd{M-b}, ...)
Run the command that is bound to the named, but uppercase, command.
@c bfox: M-a can be bound differently from M-A
@c normally, M-a looks up & runs M-A
@c if you rebind it, they're different
@c **be careful in .inputrc to bind correct case
@c is current doc of .inputrc wrong??
@item prefix-meta (@kbd{@key{ESC}})
@emph{Metafy} the next character that you type. This is for
people without a @key{META} key. @kbd{@key{ESC} f} is equivalent to
@kbd{M-f}.
@c I have no idea what the 'last thing' is.
@c empirically: successive C-- (note: I typed hyphen, not underscore) insert
@c sucessive deletions or delete a whole contiguous set of insertion (typein)
@c bfox: consecutive insertions up to n is 1 thing
@item undo (@kbd{C-_})
This is the incremental undo. Undo the last thing that you did.
@c last thing in current cmd?
You can undo all the way back to an empty line.
@c bfox: history has edits saved, so can undo them too
@item revert-line (@kbd{M-r})
Undo all changes made to this line. This is like typing the ``undo''
command enough times to get back to the beginning of your corrections
for that line.
@end table
@node Customizing Readline, vi mode, Syntax, Editing
@section Customizing @code{readline}
@c ? to define/explain: home directory, ~/ (= home dir?)
You can customize programs that use @code{readline} by putting commands
in a @code{readline} initialization file,
named @file{.inputrc}, in your home directory.
When a program (such as BASH) that uses the @code{readline} library
starts up, it checks the file @file{~/.inputrc} to set up its key bindings
and other parameters to your liking.
@c KELLEM's comments follow
@c footnote{Currently, both @code{gdb} and @code{bash} use the
@c @code{readline} library. Future interactive GNU Project programs
@c will also incorporate the @code{readline} library.}
You can also force the initialization file to be reread
(for example, if you modify it and want to use your modifications
in BASH without logging out and logging in again)
by typing @kbd{C-x C-r} (the default key binding for
@code{readline}'s @samp{re-read-init-file} function.
@c ?? re-read-init-file not documented above
@cindex @file{.inputrc} file, re-reading the
@cindex re-reading the @file{.inputrc} file
Three kinds of lines can appear in this initialization file:
@itemize bullet
@item comment
A line starting with @samp{#} is a comment.
@item key binding
@xref{Readline Key Bindings}.
@item variable setting
@xref{vi mode}.
@xref{Readline Variables}.
@end itemize
@node Readline Key Bindings
@subsection Key Bindings
@cindex readline library, customizing
@cindex editing commands, customizing
@cindex customizing readline library commands
Although the @code{readline} library comes with a set of Emacs-like key
bindings, it is possible that you would like to use different keys.
To bind a @code{readline} function to a key, place a line of the form
@example
@var{key-name}: @var{readline-function}
@end example
@noindent
or
@example
@var{key-name}: @var{readline-function} @var{comment}
@end example
@noindent
in the @file{~/.inputrc} file.
@xref{Readline Commands}, for the function names and their default key bindings.
Any text after the @var{readline-function} is considered to be a
comment and is ignored.
Key names are explained below.
For example,
@example
C-u: universal-argument
@end example
@noindent
or
@example
C-u: universal-argument used to be unix-line-discard
@end example
@noindent
binds @kbd{C-u} (which is initially bound to @code{unix-line-discard})
to @code{universal-argument} (which is not bound to any key by default).
@heading Key Names
@c needs rewriting
For the key name, you can use the name of the key combination,
such as @kbd{C-f}. The various ``words'' you can use to describe keys
are:
@table @key
@item Control-@kbd{k}
@itemx C-@kbd{k}
Holding down the control key and pressing the @kbd{k} key.
@item Meta-@kbd{k}
@itemx M-@kbd{k}
Holding down the meta key and pressing the @kbd{k} key.
@xref{Notation}, for alternative ways of metafying a key.
@item Rubout
@itemx DEL
The delete key.
@item Escape
@item ESC
The escape key, or @kbd{Control-[}.
@itemx RETURN
The enter (or return) key.
@item Space
@itemx SPC
The space bar.
@item LFD
@itemx NEWLINE
The @kbd{Control-j} key.
@item TAB
The tab key.
@end table
@heading Key Sequences
You can also specify an arbitrary key sequence instead of a single key:
@example
@var{key-sequence}: @var{readline-function} @var{comment}
@end example
To do so, surround the sequence in double quotes.
@c example
@c rewrite
If you want to use the @key{C-} or @key{M-}
specifications inside double quotes, you need to precede it with a
backslash (@samp{\}). You can also specify the escape character with
@samp{\e}. Note that you cannot use the ``words'' listed above, only:
@example
"\C-k"
"\M-k"
"\e"
@end example
@heading Macros
You can bind a key (or key sequence) to a key sequence instead of
to a named function.
@c rewrite
To do so, instead of a function name,
give the key sequence in double quotes.
Keys in this sequence are named as explained above
under ``Key Sequences''
@c example
@c format, with comment
@node vi mode, , Customizing, Editing
@subsection @code{vi} mode in @code{readline}
@cindex readline library, VI commands
@cindex VI commands in the readline library
@c KELLEM wants to change @code{vi} to @sc{vi} in this section
The @code{readline} library does not have a full set of @code{vi}
editing functions, but it does contain enough to allow simple editing of
a line.
To switch interactively between Emacs and @code{vi}
editing modes, use the command @kbd{M-C-j} (toggle-editing-mode).
@c why not listed in fns above? -- add it there
@c bfox: vi: start in insert mode
@c get into cmd mode by doing ESC; then M-C-j
@c press ESC till beeps, then M-C-j
@c beware of accidentally getting into vi mode!
To enter the @code{vi}-like editing mode directly,
without starting in Emacs mode, place the command:
@example
@code{set editing-mode vi}
@end example
@noindent
in your @file{~/.inputrc} file.
@c what about 'set -o vi...' (vs. 'set -o emacs...')
When you enter a line in @code{vi} mode, you are already placed in
``insertion'' mode, as if you had typed an @samp{i}. Pressing @key{ESC}
switches you into ``edit'' mode, where you can edit the text of the line
with the standard @code{vi} keys. Since @code{vi} is not an
officially supported Free Software Foundation product, we won't explain
the key bindings here.
@c reference?
@c KELLEM: probably should, at least, give a list of key/function list for vi
@c mode.. maybe as an appendix?
@node Readline Variables
@subsection Other @code{readline} Variables
@c KELLEM supplied most of this section's content
In addition to @code{editing-mode} (@pxref{vi mode}),
there are a number of
other variables that can be set in @file{~/.inputrc} to
affect @code{readline}'s behavior.
To set a variable, put a line of the form
@example
set @var{readline-variable-name} @var{setting}
@end example
@noindent
in the initialization file.
The current @code{readline} variables are:
@table @code
@item editing-mode
specifies the default editing mode for the
@code{readline} library. You can specify either emacs-style or vi-style
default key bindings. The default is emacs-style key bindings.
The meaningful settings of @var{editing-mode} are:
@table @code
@item emacs
@item vi
@xref{vi mode}, for more information.
@end table
@item horizontal-scroll-mode
determines how to display lines longer than the width of your display.
The meaningful settings of @var{horizontal-scroll-mode} are:
@table @code
@item Off
If @code{horizontal-scroll-mode} is set to @code{Off}
(actually, any value other than @code{On} is treated as @code{Off}), lines are
``wrapped'' when they extend beyond the width of the display.
Such a line takes more than one line on the screen,
but it still counts as a single line.
(For example, @kbd{C-a} still goes to the very beginning.)
@item On
If @code{horizontal-scroll-mode} is set to @samp{On}, the
line is shifted to the left about a third of the display's width when
the cursor extends beyond the right side of the display.
That is, the input line is scrolled between the two edges of the
screen so that the current part is visible, though other parts may not be.
@c test this
@end table
@noindent
The default value of @code{horizontal-scroll-mode} is @code{Off}.
@item mark-modified-lines
specifies whether or not to ``mark''
modified history lines with an asterisk, @samp{*}.
The meaningful settings of @code{mark-modified-lines} are:
@table @code
@item Off
Modified history lines are not marked.
@item On
Modified history lines are marked.
@end table
The default value of @code{mark-modified-lines} is @code{Off}.
@end table
@c next sec added by KELLEM
@node Inputrc File, , Other Scripts, Start-up
@subsection A Sample @file{~/.inputrc} file
@cindex inputrc file, customizing readline
@cindex inputrc file
@cindex customizing readline library, sample
@cindex readline library, sample customization file
@cindex editing commands, sample customization file
Here's an example of a simple @code{readline}
customization file, @file{~/.inputrc}:
@example
# -*- text -*-
# File: ~/.inputrc
# This file controls the behaviour of line input editing for
# programs that use the GNU Readline library. Existing programs
# include Camera, Bash, and Gdb.
#
# You can re-read the inputrc file with C-x C-r.
# Lines beginning with '#' are comments.
#
# Set various bindings for emacs_mode.
Meta-Rubout: backward-kill-word Stuff after the function name ignored
#Control-u: universal-argument
# Note that the order of the words doesn't matter.
Meta-Control-r: revert-line
Control-Meta-u: revert-line
C-Meta-T: transpose-words
M-C-k: transpose-chars
"\C-x\C-?": backward-kill-line
# This line is bad syntax. It should have the M- before the C-.
# But it works.
"\C-\M-f": forward-word
# Here is a macro definition. You can tell because the right-hand
# side is in quotes.
#"\C-xr": "\C-a\C-kemacs -f rmail\C-j\C-y"
# Bind the arrow keys. (good for sun and vt220, vt100, etc.. )
"\e[A": previous-history
"\e[B": next-history
"\e[D": backward-char
"\e[C": forward-char
# help key macro
"\e[28~": "\C-a\C-khelp | less\C-j\C-y" VT220 help key
"\e[3~": delete-char VT220 remove key
# C-r is reverse-search-history
"\e[1~": "\C-r" VT220 find key
# Select the mode.
set editing-mode emacs
set horizontal-scroll-mode On
@end example
@ignore
@c alternative for arrow keys
"\M-[A": previous-history
"\M-[B": next-history
"\M-[C": forward-char
"\M-[D": backward-char
@end ignore
@node History, Line, Editing, Top
@chapter History Substitution
@cindex history library
BASH provides facilities to remember commands and let you reuse them.
The command-history features described here are not specially programmed
into BASH.
Rather, they are provided by the history library, which is used by a
number of other GNU programs besides BASH.
(In general, programs that use @code{readline} also use history.)
This means that you can use the same history facilities
with a variety of programs.
The history library maintains a list of recent command lines, or
@dfn{events}.
@cindex event, in command history
It provides you
with functions for remembering lines on a history list,
searching through the list for a line containing an arbitrary text
string, and referencing any line on the list directly. In addition, a
history expansion function is available which allows you to easily use
those command lines again as is, or with some modifications, with very
little additional typing.
@cindex history library, using readline library instead
@cindex readline library, using instead of history library
If you find using the history library too difficult, you can use the
readline library instead (@pxref{Editing}). The readline library
includes history manipulation by default,
@c by default? is it ever not there?
and has the added advantage of Emacs-style command line editing.
@c any reason to use ! ever?
@menu
* Using History:: Using history substitution.
* Events:: How to specify which history line to use.
* Words:: Selecting words from an event.
* Modifiers:: Modifying previous events.
* History Size:: Changing the number of history lines saved.
* History Shortcuts:: History substitution shortcuts.
* History Protection:: History substitution delimiters.
@end menu
@node Using History, Events, History, History
@section How to Use History Substitution
If you type the command @code{history} on a line by itself, you are
presented with a list of events stored in the history list. For
example:
@cindex history library, how to use the
@example
bash$ history
1 cd News
2 ls
3 ls -l
4 more tobob.doc
5 mail bob
6 rm tobob.doc
7 ls
8 cat memo
9 history
@end example
@noindent
The events are numbered from the oldest command typed (in this case,
number 1) to the latest command typed (in this case, number 9).
You can re-execute any event in a history list. First you have to
determine which line from the previous history to use, then you need to
select portions of that line for inclusion in the current one.
The line selected from the previous history is called the @dfn{event},
and the portions of that line that are acted upon are called
@dfn{words}. The line is broken into words in the same fashion that
the BASH shell does, so that text surrounded by quotes is considered to
be one word (@pxref{Quotation}).
@node Events, Words, Using History, History
@section Determining Which History Line to Use
@cindex history library, events in
@cindex events, history library and
@cindex history, determining events
@c why called substitution?
By far the most common use of this @dfn{history substitution} is simply
to reuse an entire line. One way this can be done is to enter a
line which consists of @samp{!} followed immediately by enough
characters to uniquely identify the beginning of the line you want to
reuse. For example, @samp{!cat} re-runs the last @code{cat}
process (@samp{cat memo}) in the above history list:
@example
bash$ !cat
cat memo
This is a memo.
bash$
@end example
@cindex command lines, reusing
@cindex reusing command lines
@cindex history, reusing command lines
Another way to reuse a line is to follow the @samp{!} with a number,
which specifies which line in the history list to use. For example, to
reuse @samp{cat memo} we could have typed:
@example
bash$ !8
cat memo
This is a memo.
bash$
@end example
A third way is to type @samp{!?@var{string}}, which says to look
backwards through the history for the first line which contains
@var{string}. Here's yet another way of re-using @samp{cat memo}:
@example
bash$ !?memo
cat memo
This is a memo.
bash$
@end example
@cindex events, referring to
@cindex history, referring to events
As we have just demonstrated, there are several ways to refer to an
event: you can use its relative position in the history list,
@c relative position not demonstrated above?
its absolute position in the history list, or any text the event may
contain. Here is a table summarizing the various ways to refer to an
event:
@table @code
@item !!
refers to the previous command.
@item !@var{n}
refers to an event by its absolute position in the history
list. It refers to command line number @var{n}, where
@var{n} is the line number shown by the @code{history} command.
@item !-@var{n}
refers to an event by its relative position in the history
list. It refers to the command line @var{n} before the current line.
For example:
@example
bash$ echo a
a
bash$ echo b
b
bash$ !-2
echo a
a
bash$
@end example
@noindent
@samp{!-2} may be used to re-run the command prior to the last command
entered. Successive usage of @samp{!-2} may be used to cycle the last
two commands. In fact, the last @var{n} commands may be cycled through
repeatedly by using @samp{!-@var{n}}.
@item !@var{string}
refers to the most recent command @emph{beginning} with @var{string}.
@item !?@var{string}
@itemx !?@var{string}?
refers to
the most recent command containing @var{string}. The closing
@samp{?} is optional, and is necessary only when you need to separate
the event designator from additional text.
@c explain need to separate
Here's an example. Given the following two commands, entered in this
order:
@example
bash$ cp /etc/motd ~
bash$ rcp /etc/motd unsuspecting:/etc/motd
@end example
@noindent
@samp{!cp} matches the first command, while @samp{!?cp} matches the
second command.
@item !#
@itemx !:#
both refer to the current line so far. For example:
@example
bash$ echo foo !#
echo foo echo foo
foo echo foo
bash$
@end example
@end table
No matter which way you choose to refer to an event, the shell searches
its history list from the most recent event to the least recent event,
until it finds a match for your request. If your request is too
ambiguous,
@c what ambiguity is possible? all are numbers or refer to most recent
or if no such event exists, you are given an error message.
Whenever the shell sees the special character
@samp{!} in a command line, it checks the history list and makes the
appropriate substitution. There are some exceptions: if @samp{!} is
followed by a @key{SPC}, @key{TAB}, @key{RET}, @samp{=} or @samp{(}, or
preceded by @samp{<} or @samp{|}, history substitution does not take
place.
@c should samp's in above be kbd's? should key's be wrapped in kbd's?
@c why are those contexts exceptional? what DOES happen?
@c why not also preceding b [, for filename patterns?
@node Words, Modifiers, Events, History
@section Words Within Events
@cindex history, words in
@cindex history, selecting words
@cindex words, selecting from history
It is possible to select and use only portions of an event. You can
select any word, or series of words, from an event. Several words
surrounded by quotes are considered to be one word.
@c single quotes? double quotes?
The words of an event line are numbered from left to right, with the
first word (the command name) being 0. For example:
@example
bash$ echo one two three four five
@end example
@noindent
In this example, word 0 is @code{echo}, and word 5 is @code{five}.
To specify a particular word from a previous event, follow the event
specification with a colon, @samp{:}, and a designator for the desired
word, or words, from that event. The word designators are:
@c must define 'event spec' above
@table @code
@item 0
The number 0 represents the first word, which is almost always the
command name.
@item @var{n}
This matches the @var{n}'th word.
@item ^
This is a special notation representing the first argument (that is,
word 1).
@item $
This is a special notation representing the last argument.
@item %
This represents the word matched by the most recent pattern search,
@code{?@var{string}@r{[}?@r{]}}.
@item @var{x}-@var{y}
This matches a range of words.
@c inclusive
@item -@var{y}
This is equivalent to the range @code{0-@var{y}}.
@item *
This matches all the words after word 0, up to and including the last
word. This is similar to matching the range @code{^-$}, except
@code{*} can match 0 or more words, while @code{^-$} must match 1 or
more words.
@item @var{x}*
This is equivalent to the range @code{@var{x}-$}.
@item @var{x}-
This is equivalent to the range @code{@var{x}-($-1)}.
@c what's that useful for? looks bizarre
@end table
The @samp{:} that separates the event specification from the word
designator can be omitted if the word designator begins with a @kbd{^},
@kbd{$}, @kbd{*} or @kbd{%}.
@c but not - ?
When referring to the immediately
preceding command, you can omit the line identifier if you want.
Therefore, @samp{!:2} refers to word 2 in the previous command line.@refill
Note that @samp{!} alone on a line means nothing in terms of history
expansion. Also, if an event contains more than one command line
separated by semicolons, the semicolons count as words too.
Here are several examples using the various word designators in the
above table:
@example
bash$ mkdir /nfs/cwjcc/fs2/src/Gnu/src/bash/1.06
bash$ mv bash.tar.Z !$
mv /nfs/cwjcc/fs2/src/Gnu/src/bash/1.06
bash$ cd !$
cd /nfs/cwjcc/fs2/src/Gnu/src/bash/1.06
@end example
@c should the mv response include bash.tar.Z ??
@noindent
This example uses the shorthand for the last word on a command line to
avoid typing in a lengthy path name more than once.
@c show equivalent & explain that !=prev cmd, $=last wd
@c need a REAL example
@example
bash$ echo a
a
bash$ !! b
echo a b
a b
bash$ !! c
echo a b c
a b c
bash$ echo !*
echo a b c
a b c
@end example
@c above, shows expanded cmd before does it.
@c not all examples do, but all should
@noindent
This example demonstrates how you can build up a command line
with successive applications of the @samp{!!} notation. You then use
the @samp{!*} expansion to make use of all arguments accumulated so
far.
@example
bash$ cc -o prog -g a.c b.c c.c
bash$ cmd=!:0 output=!:2 optimize=!:3 files="!:4-$"
@end example
@c what's cc, what's cmd= ?
@noindent
@c explain
This shows one possible use of the history facilities to break up
command lines into individual elements. After the second command, the
individual portions of the command may be reused, perhaps to print the
source files just compiled with @samp{lpr $files}.
@node Modifiers, History Size History, Words, History
@section Modifying Previous Events
@cindex history, modifying previous events
@cindex events, modifying previous
@cindex modifying previous events
Sometimes you don't want to re-execute an event exactly.
Perhaps you
mis-typed a file name, or want to substitute a new pathname, or a
different argument. Whatever the reason, you can modify an event, or
any word of an event, by following that event with a colon, @samp{:},
and a modifier.
Here is a list of modifiers and their explanations:
@c terminology to explain: pathname, head, filename extension, basename, tail
@table @code
@item h
This removes the last element of a pathname, leaving the only the @emph{head}.
@item r
This removes a filename extension, or trailing suffix
@samp{.@var{xxx}}, leaving only the @emph{root}.
@item e
This removes all @emph{but} the filename @emph{extension}, or trailing suffix
@samp{.@var{xxx}}.
@item t
This removes all of the leading pathname components, leaving only the
@emph{tail}.
@item s/@var{string1}/@var{string2}
This @emph{substitutes} the value of @var{string2} for @var{string1} the
first time it appears. If the @code{g} flag is given as well, the
changes take place globally; that is, all occurrences of @var{string1}
are replaced with @var{string2}.
@item p
This @emph{prints} the new command but does not execute it. This
allows you to preview the effects of modifiers safely.
@c s and gs added by KELLEM
@item s/@var{this}/@var{that}
substitutes the first occurrence of @var{this} with @var{that} on
the specified history line.
@item gs/@var{this}/@var{that}
globally substitutes @var{this} with @var{that} on the specified
history line.
@end table
The modification is applied only to the first applicable word
on the line. If there are two or more occurrences on that line, the
subsequent occurrences are not changed. If no word on the line is
applicable, then you get an error message.
Here are some examples of reusing command lines with slight
modification:
@example
bash$ diff -c2 old/shell.c shell.c > shell.diffs
bash$ !!:gs/shell/builtins
diff -c2 old/builtins.c builtins.c > builtins.diffs
@end example
@noindent
This example demonstrates the use of the substitution mechanism to
re-run a command. This example may be used repeatedly to create
``diffs'' of a number of changed files without retyping the lengthy
command each time.
@example
bash$ echo /a/b/c/d
bash$ head="!:1:h" tail="!:1:t"
bash$ echo $head $tail
/a/b/c d
@end example
@c what's the = ? variable setting?
@noindent
This shows a possible use for the filename splitting facilities.
@example
bash$ edit file.c
bash$ f="!:1:r" ; echo making $@{f@}.o ; make $@{f@}.o ; unset f
@end example
@noindent
This is a rather clumsy way to remake an object file from a
just-modified source file. While this example shows the use of the
history library, there are easier ways to remake an object file. For
example you can encapsulate the @code{echo} and @code{make} into a
function, like this:
@c ?
@example
bash$ type make_o
make_o is a function
make_o ()
@{
echo making $@{1@}.o
make $@{1@}.o
@}
bash$ edit file.c
bash$ make_o !:1:r
make_o file
@end example
@node History Shortcuts, History Protection, History Size History, History
@section Shortcuts
@cindex command lines, making changes to
@cindex command lines, history library and
A @samp{^} at the beginning of a command line is a special way to
designate that you want to make changes, or corrections, to the
previous command line. In this case, @samp{^} is equivalent to
@samp{!:s^}, and provides a convenient and special shorthand for making
substitutions to the (immediately) preceding event. The syntax for
this substitution is:
@example
^@var{old}^@var{new}
@end example
@noindent
The @var{old} characters between the two @samp{^} are replaced by the
@var{new} characters following the second @samp{^}. For example:
@example
bash$ mroe parse.y
bash: mroe: command not found
bash$ ^mroe^more
@end example
@noindent
The first command contained a spelling error, resulting in an unknown
command. Using the quick substitution feature, we can rerun the
command with the correct spelling substituted.
@node History Protection, , History Shortcuts, History
@section Delimiters
You can delimit a history substitution from the characters that follow
it by surrounding that substitution with @samp{@{}and @samp{@}}. For
example:
@example
bash$ make flags.o
@r{[} errors compiling flags.c @r{]}
bash$ edit @{!$:r@}.c
@end example
@c explain: !... means last arg basename, namely 'flags'
@noindent
In the above example, we attempt to use the @code{make} command to
create @file{flags.o} from @file{flags.c}. There are errors in
@file{flags.c}, so history substitution is used to create the name of
the source file so that it can be edited.
@c can't understand next paragraph -- what makes the {} a NOP?
@c also, if braces not needed here, need better example.
While braces are not strictly necessary in this example, note that the
braces are not treated specially by the history substitution mechanism
in any way. This works because brace expansion is enabled on our
version of BASH. @emph{If brace expansion is not enabled, enclosing a
history substitution in braces will cause those braces to be retained.}
@node Quotation, , echo, File Names
@chapter Preventing Shell Interpretation of Special Characters
@c Is quoting for other parts of commands too, or just for wildcards?
@c (Current chapter separated from old wildcard chapter)
@c sounds more general
@cindex command lines, quoting
@cindex quoting
There are times when you want the shell to treat special characters as
regular characters, and not expand or interpret them.
@c what does 'interpreted' mean? different from 'expanded'?
To do this,
you must @dfn{quote} the special character by preceding the character
with a @samp{\} or by surrounding the character (or part of
the argument containing it) with single or double quotes.
@c justification? isn't it bad & very rare to have file names with
@c special chars in them?
@table @code
@item \
The backslash, @samp{\},
forces the character that follows it to have its literal
meaning, suppressing any special interpretation in the shell.
Exception: A
backslash followed by a newline character signifies a continuation of
a shell command line onto the following line (@pxref{Continuation}).
@c newline=RET ?
Note that the backslash protects a single character, not a string
of characters.
For example, @samp{rm bad*name} deletes all files whose names start with
@samp{bad} and end with @samp{name}, whereas @samp{rm bad\*name} deletes
only the file named @file{bad*name}. The @samp{\} prevents the shell
from interpreting the @samp{*} as a wildcard.
You can protect the backslash itself from being interpreted by the
shell by preceding it with another backslash.
@c example
@item '@dots{}'
Single quotes turn off the special meanings of @emph{every} character
between them. All these characters are taken literally. This allows
you to include blank characters in a string. For example:
@c huh? why are blanks interesting? how relate to file names?
@c '...' equivalent to \ in front of every char?
@c what does example have to do with wildcards?
@c what are such strings for?
@example
'This $#?!!# sentence is taken literally.'
@end example
@c example with > 1 wildcard instead? e.g. rm bad?*name vs.
@c rm bad'?*'name = rm 'bad?*name'
Note that even the backslash character is treated literally between
single quotes. Therefore, there is no way to include single quotes
themselves in the string.
@c explain or remove
@item "@dots{}"
Double quotes turn off the special meanings of every character between
them @emph{except} @samp{$}, @samp{'}, and @samp{\}. The characters
@samp{$} and @samp{'} retain their special meanings within double
quotes. When surrounded by double quotes, the backslash, @samp{\},
retains its special meaning only when followed by @samp{$}, @samp{`},
@samp{"}, @samp{\}, or the newline character.
@c whole "" section has no clear relation to filename wildcards
For example:
@c example not related to file names
@example
"The value of test is $test."
@end example
You can protect a double quotation mark from being interpreted by the
shell by preceding it with the backslash character, as in @samp{\"}.
A double quote may be quoted within double quotes by preceding it
with a backslash.
Warning: the special parameters @samp{$*} and @samp{$@@} have special
meanings when inside double quotes (@pxref{Predefined}).
@end table
@c following par: need examples of why/when need such chars quoted
You should quote any special character if you
do not want the shell to use that character's special meaning.
Therefore quote all redirection operators, wildcard characters,
command-line characters, quote characters, and grouping characters if
they are to represent themselves. In particular, the following
characters should be quoted if they are to represent themselves:
@cindex quote, when to
@example
! | & ; < > ( ) $ ` ' " \ * ? [ ] #
@end example
@c above is all special chars? what about : { } (others?)
@noindent
In addition, you should always quote the space, tab, and newline
characters if they are not to be interpreted by the shell. You can
use single or double quotes around an entire argument or word, or
around just part of one. For example:
@example
make CC="cc -O"
@end example
@noindent
shows how to specify @samp{cc -O} as the compilation command.
@node Advanced Redirection
@chapter Redirecting Input and Output (Advanced)
@node Other Redirections, Pipes, Here-documents, I/O
@section Redirection Using File Descriptors
@cindex redirection operators, with file descriptors
@cindex file descriptors
@cindex standard input, redirecting
@cindex standard output, redirecting
@cindex standard error, redirecting
@cindex redirecting input and output
The basic redirection operations (@pxref{Redirection})
are actually special cases of a more general mechanism for
affecting the input and output files used by programs.
Programs actually do their input and output in terms of @dfn{file
descriptors} (non-negative integers) that are associated with files or
devices.
@c bfox: file descr is index to array of file info
For example, a program might read from file descriptor 3 and
write to file descriptors 6 and 8.
The redirection operators are a means of associating open files with
file descriptors, so that such a program will use the desired files.
In order for the shell to be able to set up command input and output
in simple, general ways -- hooking commands together with pipes
(@pxref{Pipes}) or redirecting input and output to files as shown
earlier (@pxref{Redirection}) -- certain conventions have been
established for file descriptors. Descriptors 0, 1, and 2
are generally used as follows:
@table @asis
@item 0
is called @dfn{standard input}.
Programs usually read their input from standard input.
@cindex standard input, file descriptor 0
@item 1
is called @dfn{standard output}.
Programs usually write their output to standard output.
@cindex standard output, file descriptor 1
@item 2
is called @dfn{standard error}.
Programs usually write their error messages to standard error.
@cindex standard error, file descriptor 2
@end table
Other file descriptors have no standard meaning.
You can redirect any file descriptors you like, but
not all redirections make sense. In particular, redirecting a file descriptor
number that the program doesn't use will have no effect.
In general, a redirection using file descriptors looks like this:
@ignore
@c they were each shown with args, but it's probably better to consider
@c those as part of the command. E.g. it was:
@var{command} @r{[}@var{arguments}@r{]} @r{[}@var{n}@r{]}> @var{m}
@end ignore
@example
@var{command} @r{[}@var{n}@r{]}@var{redirection-operator} @var{m}
@exdent @r{or}
@var{command} @r{[}@var{n}@r{]}@var{redirection-operator} @var{file}
@end example
@noindent
where @var{n} (which is optional) and @var{m} are file descriptors,
@var{file} is a file,
and the @var{redirection-operator} is as described below.
Warning:
If @var{n} is supplied, there must not be any space between it
and the operator.
If the file descriptor @var{n} is omitted and the first character of
the redirection operator is @samp{<}, @var{n} defaults to the
standard input (file descriptor 0). If @var{n} is
omitted and the first character of the redirection operator is
@samp{>}, the @var{n} defaults to the standard output (file
descriptor 1).
@table @code
@item @var{n}> @var{file}
@itemx @var{n}>| @var{file}
@itemx @var{n}>> @var{file}
open @var{file} for output on file descriptor @var{n}.
@var{n} defaults to 1 (standard output).
Thus the operators @samp{>}, @samp{>|}, and @samp{>>} described earlier,
which redirect standard output, are equivalent to @samp{1>}, @samp{1>|},
and @samp{1>>} respectively.
@cindex @code{>} operator, with file descriptor
@cindex @code{>|} operator, with file descriptor
@cindex @code{>>} operator, with file descriptor
@c following itemize is exact copy from basic chapter
@itemize @bullet
@item
If @var{file} doesn't yet exist, it is created.
@item
If @var{file} already exists:
@itemize @bullet
@item
With @samp{>} and @samp{>|}, @var{file} is erased before the
first output is written to it. Be careful:
If a file of the same name already exists,
its contents are deleted before your command's output is
written to that file.
If you don't want @samp{>} to erase existing files, set the
shell's @code{noclobber} variable; then
@samp{>} with an existing file will generate an error message and leave
the file alone. (But note that @samp{>|} will clobber existing files
regardless of the setting of the @code{noclobber} variable.)
@item
With @samp{>>}, the output is appended to the end of an existing @var{file}.
@end itemize
@end itemize
For example:
@example
bash$ find / -name resume -print 2> /dev/null
@end example
@noindent
This command looks for and prints the pathnames of all files
named @file{resume} by traversing all directories under the @file{/}
directory. When @code{find} encounters permission problems (for
example, directories it does not have permission to read) it prints an
error message on standard error. The above redirection @samp{2>
/dev/null} forces all these error messages to be written to the special
file @file{/dev/null}, which simply discards these messages so that
only the requested @file{resume} files are printed on standard output.
This saves you from wading through pages of uninteresting error messages
from @code{find}.
@c rewrite in terms of utility for redirecting just error w/o output
@item @var{n}< @var{file}
opens @var{file} for input on file descriptor @var{n}.
@var{n} defaults to 0 (standard input).
Thus the operator @samp{<} described earlier, which redirects standard
input, is equivalent to @samp{0<}.
@cindex @code{<} operator with file descriptor
@c what if n=1 or 2(output)?
@c I tried 'who 1< foo' . Got err msg if foo not exist, no err msg but
@c also no output if foo existed (foo left untouched)
@c bfox: probably who wrote to 1, but it was open for read, not write,
@c but who didn't check for errors on write
@cindex redirection operators, reading and writing
@item @var{n}<> @var{file}
opens @var{file} for both reading and writing on file descriptor @var{n}.
@var{n} defaults to 0 (standard input).
@cindex @code{<>} operator, redirecting input and output
As with @samp{>} (above), an existing @var{file} is erased before the
first output is written to it unless the shell's @code{noclobber}
variable is set (in which case @samp{<>} with an existing file will
generate an error message and leave the file alone.)
@item @var{n}>& @var{m}
makes the file descriptor @var{n} be a copy of the file descriptor @var{m}.
@var{n} defaults to 1 (standard output).
@c no requirement that n and/or m be output descriptors?
@c n=0(input) seems harmless
@c what if m=0(input)? 1>&0 seems to be NOP w no msg
@c e.g. date 0<foo 1>&0 sends output (1) to tty, not to foo
@cindex @code{>&} operator with file descriptor
Thus the redirection @samp{>&@var{file}} described earlier, which
redirects standard output and standard error to the @var{file},
is equivalent to @samp{>@var{file} 2>&1}.
For example :
@example
bash$ make >make.log 2>&1
@end example
@noindent
@code{make} produces output both on the standard output (as it executes
commands) and on the standard error (in the case that a file didn't
compile correctly, etc.).
The first redirection operator on the line says to send output for
the standard output into a file called @file{make.log}.
The second redirection causes
output to file descriptor 2 (the standard error) to be output wherever
the output from file descriptor 1 is going (the standard output).
Thus, both the standard error and standard output are written to
@file{make.log}. (There is a shorthand for
redirecting both the standard output and the standard error to a single file.
@xref{Redirection}, @samp{>&@var{file}}.)
@item @var{n}<& @var{m}
makes the file descriptor @var{n} be a copy of the file descriptor @var{m}.
@var{n} defaults to 0 (standard input).
(Note that @code{@var{n}<& @var{m}} and @code{@var{n}>& @var{m}} behave
identically except when @var{n} is omitted, in which case they have
different defaults.)
@cindex @code{<&} operator with file descriptor
@c note: (bfox) >&- same as <&-, only diff is default value of n
@item @r{[}@var{n}@r{]}>&-
closes the file descriptor @var{n}.
@var{n} defaults to 1 (standard output).
@c bfox: closes file & removes association of file w. n
@item @r{[}@var{n}@r{]}<&-
closes the file descriptor @var{n}.
@var{n} defaults to 0 (standard input).
(Note that @code{@r{[}@var{n}@r{]}<&-} and @code{@r{[}@var{n}@r{]}>&-}
behave identically except when @var{n} is omitted, in which case they
have different defaults.)
@end table
@heading Multiple Redirections
More than one redirection operator can appear in a command.
@cindex redirection operators, using multiple
@emph{The order in which redirections are specified is important.} The
shell evaluates redirection operators in the order encountered, from
left to right. A file descriptor specified with an earlier
redirection operator can be used by a subsequent redirection. For
example:
@c strange example: plain >& does it without file descriptors
@example
ls > error-list 2>&1
@end example
@noindent
redirects first the standard output (@code{>})
and then the standard error (@code{2>&1}) to the
file @file{error-list}, while the command:
@c strange example: plain > does it without file descriptors
@example
ls 2>&1 > error-list
@end example
@noindent
redirects only the standard output to the file @file{error-list}. The
first redirection operator @code{2>&1}
makes the standard error (2) be a copy of the
standard output (1) @emph{before} the standard output is redirected to
@file{error-list} with @code{>}.
@heading Redirection in Pipelines
Each command in a pipeline may
include redirection operators. These redirections are performed after
the pipes that link the commands are created.
That is, first the standard input and standard output of each command
in the pipeline are set up as specified by the pipes, then any
redirections specified in the commands are performed.
Thus such a redirection can access the standard input and output set up
by the pipeline. For example, @samp{2>&1} in the first command in
a pipeline makes that command's standard error be the same as its standard
output, hence sends the command's error messages along with its ordinary
output to the second command in the pipeline.
@node Here-documents, Other Redirections, Redirection, I/O
@section Redirection to Shell Scripts
@c what are << and <<- for? shellscripts? probably not a good idea at
@c tty, so examples with prompts are poor.
@c bfox: also good in functions
@c Posix p.172 calls it 'here-document' in 'shell input file'
@c add Intro here to explain it.
@c bfox: say it is traditionally called here-document
In general, such a redirection of input looks like this:
@ignore
@c they were each shown with args, but it's probably better to consider
@c those as part of the command. E.g. it was:
@var{command} @r{[}@var{arguments}@r{]} << @var{word}
@end ignore
@example
@var{command} @var{redirection-operator} @var{word}
@end example
@noindent
where the @var{redirection-operator} is as follows,
and spaces surrounding it are optional:
@table @code
@item <<
instructs the shell to read input for @var{command}
from the same place as the shell is reading commands from.
The shell reads lines
until a line containing only the given @var{word} (with no trailing blanks) is
seen. All of the lines read up to that point are considered the input
for the @var{command}.
@cindex @code{<<} operator
For example:
@c example was CAT << foo, but sort seems more interesting.
@c Need a real example.
@example
bash$ sort << foo
hip
hip foo
hooray
and
foo
and
hip
hip foo
hooray
bash$
@end example
@noindent
The four lines after @samp{sort << foo} became the input to the
@code{sort} command. The fifth line, containing @samp{foo} on a line by
itself, marked the end of the input. (Note that the @samp{foo} in the
second input line did not end the input because the line contained other
text as well.) The four lines after the end of the input are
the output of the @code{sort}, namely the input lines in alphabetical order.
@item <<-
@samp{<<-} is like @samp{<<}, except that leading tab characters are
stripped from each line of input as it is read.
@c how justify version that strips tabs - bfox: for formatting?
@cindex @code{<<-} operator
@end table
@c Posix says can have more than one <<, <<- in command.
@c cover that? True of any other redirection operators?
@node Grouping
@chapter Grouping Commands
@c placeholder for stuff to rewrite completely
@c new concept: subshell, shell environment, [non]interactive shell
@table @code
@item @{ @var{list}; @}
@c what is format of the list?
Curly braces are used to group commands. The list of commands is
executed in the current shell environment. The curly braces
must either begin a line, follow a @samp{;}, or be surrounded with
whitespace for the shell to recognize them as grouping commands. For
example:
@cindex commands, grouping
@cindex grouping commands, using @{ @}
@example
bash$ foo=bar
bash$ @{ ls -l ; echo "Listing finished."; echo $foo @} >listing
@end example
@noindent
lists the files in the current directory, outputs ``Listing finished.'',
and outputs ``bar'', all of which is redirected into the file
@file{listing}. Unlike the following example, the grouping commands do
not start a subshell, so the current shell's variables are available for
use.
@item (@var{list})
@c what is format of the list?
The list of commands is executed in a subshell. Variable assignments
and built-in commands that affect the shell's environment do not remain
in effect after the command finishes.
@cindex grouping commands, using ( )
@cindex commands, grouping
The fact that commands within parentheses are executed within a
subshell means that the parent shell is unaffected by shell
side-effects of those commands. Changes in shell state caused by
commands executed in a @emph{subshell} do not affect the parent shell.
Let's illustrate:
@c silly example -- the cd in the subshell is useless
@example
bash$ pwd
/home/alan/work
bash$ (cd ..)
bash$ pwd
/home/alan/work
bash$ cd ..
bash$ pwd
/home/alan
bash$
@end example
@noindent
In this example, the current working directory is
@file{/home/alan/work} as shown by the output of the @code{pwd}
command. The command @code{(cd ..)} executes in a @emph{subshell} so
that it does not change the current directory of the parent shell and
the user remains in the original directory, @file{/home/work/alan}.
However, when the command @code{cd ..} is executed in the parent shell
(that is, it is executed without being surrounded by parentheses) the
parent shell's current working directory is changed to
@file{/home/alan}.
@end table
@node Aliases, Functions, Line, Top
@chapter Aliases
@cindex alias
@cindex shorthand, command names
@cindex command name shorthand
Aliases are a way to rename, redefine, or otherwise rearrange commands
to your liking. An alias is created using the following syntax (note
that there cannot be any spaces before or after the @samp{=} sign):
@example
alias @var{name}=@var{expansion}
@end example
@noindent
The @var{name} is the command-name shorthand you want to enter at the
shell prompt. The @var{expansion} is the command that
the @var{name} will stand for. For example:
@example
alias more=less
@end example
@noindent
causes the program @code{less} to be substituted for the operating
system's @code{more} program every time the word @samp{more} is typed.
@c next sec says: any time typed as command part (1st part) of cmd
@c ? I don't understand this text & example
@c see kellem's example below
If the last character of the value for the alias,
@var{expansion}, is a blank, then the word following the alias
will also
@c ? also = in addition to the cmd part of the line?
be checked for substitution. For example:@refill
@example
alias time='time '
@end example
@noindent
allows you to time a command for which you have defined an alias. With
this alias you can time what you would be running if you typed the
expanded version as a command.
For example, let's say you defined an alias @samp{alias more=less}.
Normally, if you type @samp{time more}, @file{more} is
timed. However, if the @samp{time} alias has been previously defined,
typing @samp{time more} times @file{less}, which is
what you want. The alias @code{more} is expanded, and its value
(@code{less}) is substituted as the program to time.
If the value for the alias, @var{expansion}, contains spaces,
tabs, or metacharacters,
@c ? metachar means M-... ? What's reason to include metas, not C- etc.?
you must enclose that definition in quotes
to avoid misinterpretation by the shell. For example,
let's say that you use the command-option sequence @samp{ls -la} at
lot. You can assign this command to the alias @code{la} to
make typing quicker and easier:
@example
alias la='ls -la'
@end example
@noindent
Now you can type @samp{la} instead of @samp{ls -la} when listing files.
@c KELLEM: you can make aliases for arbitrary text,
@c that is all an alias really is (a text substitution). can be useful for
@c bash$ alias foo=some.host.somewhere
@c bash$ alias rlogin="rlogin "
@c bash$ rlogin foo
@c is same as `rlogin some.host.somewhere'
@cindex aliases, listing
To get a list of all the currently defined aliases, simply type the
@code{alias} command with no arguments. A list of aliases in the form
@samp{@var{name}=@var{value}} is displayed on the standard output. If
you want to know if a specific shorthand name has any aliases, you can
type:@refill
@example
alias @var{name}
@end example
@noindent
This tells you if any aliases exist for that specific @var{name}.
@cindex aliases, the shell and
Aliases are local to the shell in which they were declared. This means
that aliases can't be used within shell scripts @emph{unless those
aliases were declared in that script}. This means that the alias
command has to be executed in the shell script before the command which
references that alias is read.
It also means that aliases disappear when their shell is terminated.
@emph{BASH aliases cannot be exported to another shell.} To get BASH
to remember an alias permanently, you have to enter that alias in your
login file (@pxref{Start-up}).
@menu
* Advanced Aliasing:: Creating aliases for complex commands.
* Remove:: Removing aliases.
@end menu
@node Advanced Aliasing, Remove, Aliases, Aliases
@section Creating Aliases For Complex Commands
@cindex aliases, complex
@cindex aliases, string substitution and
@cindex string substitution and aliases
While you can use simple string substitution with aliases, note that
the @code{alias} command is limited to expanding only the first word in
a command. Using pipes, @samp{|}, semicolons, @samp{;},
@samp{&&} (@sc{and}) and @samp{||} (@sc{or}), it is possible to have more
than one command sequence per command line.
@c ? terminology problem is killing us here -- command meaning either
@c prog to run or simple cmd with args or compound command
In this case, you can have
more than one alias on the command line, but you can still only have
one alias per command. For example, let's create two more
aliases:@refill
@example
bash$ alias listdir='ls'
bash$ alias linecount='wc -l'
@end example
@noindent
and combine those aliases on one command line:
@example
bash$ listdir | linecount
@end example
@noindent
The @code{alias} command expands @code{listdir} to @code{ls} and
@code{linecount} to @code{wc -l} because @code{listdir} and
@code{linecount} begin @emph{separate} commands.@refill
@cindex aliases, versus functions
@cindex aliases, using functions instead of
@cindex functions, versus aliases
@cindex functions, using instead of aliases
If you need more complicated expansion in a command line, use a shell
function (@pxref{Functions}). In particular, there is no mechanism in
BASH for using arguments in the replacement text of aliases. If
arguments are needed, a shell function should be used instead of an alias.
@cindex aliases, multiple commands and
@cindex multiple commands, aliases and
You can also make aliases that represent multiple commands. For
example, you can create an alias that goes to a directory of your
choice (@code{cd}), lists what is in that directory in long form
(@code{ls}), and shows you the
total disk space used by that directory (@code{du}):
@c KELLEM: dashes are not allowed in POSIX.2 draft 10 in aliases (not a valid
@c shell identifier), I believe. 'course, the dashes are fine with me. :-)
@example
alias m-use='cd /usr/spool/mail; ls -la; du'
@end example
@noindent
To use this alias, just type @code{m-use}.
@c ref for keywords? Is there a list of keywords somewhere?
Lastly, you can alias keywords. For example, if you would rather end
the @code{do} part of a loop command (@pxref{Conditionals and Loops})
with @code{od} than with the normal @code{done}, you can
@example
bash$ alias od=done
bash$ for i in 1 2 3
> do
> echo $i
> od
1
2
3
@end example
@node Remove, , Advanced Aliasing, Aliases
@section Removing Aliases
@cindex aliases, removing
@cindex removing aliases
@cindex @code{unalias} command
@cindex aliases, the @code{unalias} command
To get rid of aliases, use the @code{unalias} command. This command
looks like this:
@example
unalias @var{name1} @var{name2} @dots{} @var{nameN}@refill
@end example
@noindent
The @code{unalias} command removes all the named aliases from the list
of defined aliases. For example:
@example
unalias m-use
@end example
@noindent
removes the @code{m-use} alias, if present.
@node Variables, Environment, Scripts, Top
@chapter Shell Variables
@c need new introduction
@c bfox: home etc.: bash tries to get from env, if not there, creates
@c * etc. are really predefined
@c 5 kinds of vars:
@c inherit or create (e.g. home)
@c predefined (*, @, ...)
@c magic vars -- auto_resume, noclobber -- control shell's internal operation
@c user vars
@c dynamic vars -- seconds, etc.
@c to coordinate -- what is explained here vs. customization chapter re
@c how to set/unset a var, see its value, etc.
@cindex variables, what are
@cindex shell variables
@cindex shell variables, types of
@node Variable Mechanics
@section Mechanics of Named Variables
Shell behavior that depends on a variable may depend on:
@itemize
@item
the value of the variable
@item
whether the variable exists (is set), independent of what value it has
@end itemize
Thus, in order to configure a shell variable to get the effect you want,
you may need to know:
@itemize
@item
how to tell whether a variable exists (is set)
@item
how to create (set) a variable
@item
how to unset a variable (make it cease to exist)
@item
how to find out the value of a variable
@item
how to change the value of a variable
@end itemize
To find out the value of a variable, type
@samp{echo $@var{name}}, where @var{name} is the variable of interest.
(Be sure to include the @samp{$}: If you omit it, @code{echo} just
repeats the @var{name} itself.)
@itemize
@item
If something is printed, that is the value of the variable.
@item
If nothing is printed, then either the variable exists and has a null
(invisible) value, or the variable does not exist.
@end itemize
@noindent
More generally, to get the value stored in a variable, precede the variable's
name by a dollar sign, @samp{$}.
@c explain what 'more generally' is
To set a variable (create a new variable or change the value of
an existing variable), type
@samp{@var{name}=@var{new-value}},
where @var{name} is the variable you want to set and
@var{new-value} is the value you want it to have.
Don't leave any blank space around the @kbd{=}.
If you just want to create the variable, and don't need to give it any
particular value, you can simply omit the @var{new-value}
and type @samp{@var{name}=}.
The name of a shell variable must start with a letter or an underscore
and it can contain only letters, digits, and underscores.
Uppercase and lowercase letters are not equivalent in names.
Be careful to type variable names correctly:
If you type a name wrong before an @samp{=}, you will either change
the wrong variable or create a new variable.
To include whitespace (spaces, tabs, or newline characters) in a
variable's value, either quote the value with @code{"@dots{}"} or
@code{'@dots{}'}, or precede each whitespace character with a backslash,
@samp{\} (@pxref{Quotation}).
@c bfox: this stuff is done at assignment time
@c Value undergoes tilde expansion, parameter and variable expansion,
@c command substitution and quote removal.
To get rid of a variable, type @samp{unset @var{name}},
where @var{name} is the variable of interest.
To find out whether a variable exists, you can do any of the following:
@itemize
@item
Type @samp{set} to get a listing of all your shell variables in
alphabetical order, and see if the variable is in the list.
@item
Type @samp{set | grep @var{name}=}.
If the variable @var{name} exists, its name (and value, if non-null) will be given;
otherwise there will be no output.
@item
Type @samp{set -u}
@c substitute new equivalent: something like
@c set -o nounset
to tell the shell to make @code{echo} of an unset
(nonexistent) variable give an error message.
From then on, @samp{echo $@var{name}} will be different for nonexistent
variables than for variables with null values.
@end itemize
Warning: @code{set} and @samp{unset} are not inverse commands:
Although @code{unset} unsets shell variables, @code{set} does not set
them.
@node Variable Examples, Positional, Variables, Variables
@subsection Examples with Named Variables
@c need more examples
@c may integrate with parent section (mechanics)
Here are some examples of user-defined variables:
@example
bash$ test=This\ is\ a\ test
bash$ test_2="This is also a test"
bash$ test_3='Yet another test'
bash$ echo $test
This is a test
bash$ echo $test_3
Yet another test
@end example
To prevent @samp{$} from meaning ``evaluate the following variable,''
precede the @samp{$} with a backslash, @samp{\}, or enclose @samp{$} and
the reference in single quotes.
@c note: not double quotes
@c explain diff between single & double quotes
For example:
@example
bash$ echo \$test
$test
bash$ echo '$test'
$test
bash$ echo $test
This is a test
@end example
@node Positional, Predefined, User-definable, Variables
@section Positional Parameters
@cindex positional parameters
A program, shell function, or shell script needs a way to refer to
arguments passed to it on the command line that invoked it. The shell
provides for this by means of special variables called @dfn{positional
parameters}.
The name of a positional parameter is a positive integer.
The value of a positional parameter is whatever the shell assigns
it from a command line, or whatever you assign it with
@code{set} or @code{shift} (described below).
To evaluate a positional parameter, precede its
name by a dollar sign, @samp{$}, just as you would a named variable.
But if the parameter name is longer than a single digit, you must
enclose it in braces. For example, you'd type
@kbd{$@{10@}} to refer to the value of parameter @samp{10}.
When you give a command, the arguments are put into consecutive
positional parameters starting with @code{1}.
For example, assume we have a script named @code{args}
that simply echoes its first two arguments to the standard output.
That is, the script contains just the command
@samp{echo $1 $2}. Then @code{args} behaves as follows:
@example
bash$ args 1 3
1 3
bash$ args hi there
hi there
bash$ args hi there everybody
hi there
bash$
@end example
@xref{Predefined}, for information about the parameter @code{0},
which holds the name of the current command,
the parameters @code{*} and @code{@@}, which refer to all
the positional parameters at once, and the parameter @samp{#},
which holds the number of positional parameters (the current
number of arguments).
The @code{set} command can be used to assign new values to positional
parameters. The command
@example
set @var{values}
@end example
@noindent
assigns the given @var{values} to consecutive positional parameters
starting with @code{1}. For example, if we augment the above
@code{args} script to be
@example
echo $1 $2
set new message
echo $1 $2
@end example
@noindent
then it will modify its positional parameters, replacing the
command-line arguments with @code{new} and @code{message}, and will behave
as follows:
@example
bash$ args hi there everybody
hi there
new message
bash$
@end example
The @code{shift} command moves each positional parameter's value
into the parameter to its left.
The value of @code{2} is moved into @code{1}, the value of @code{3}
is moved into @code{2}, and so on.
The last parameter becomes null.
@c bfox: used to determine whether any args left on line -- example?
This is useful, for example, in a recursive shell function,
to ``cdr down'' the list of arguments.
@code{shift} can also take a numeric argument:
@example
shift @var{n}
@end example
@noindent
This causes the positional parameters to be shifted left
@var{n} positions instead of just 1 position.
The value of parameter @var{n+1} is moved into @code{1}, and so on.
For example, if we modify the above @code{args} script to be
@example
echo $1 $2
shift 2
echo $1 $2
@end example
@noindent
then it will behave as follows:
@example
bash$ args hi there everybody else
hi there
everybody else
bash$
@end example
BASH itself also has positional parameters, which you can @code{set},
@code{shift}, and examine.
The positional parameters seen by a command are distinct from
those of the invoking shell.
In this example, we set the shell's first three positional parameters
and see that they are unaffected by execution of the @code{args}
command defined above, which uses @samp{echo $1 $2} to echo its first two arguments.
@example
bash$ set one two three
bash$ echo $1 $2
one two
bash$ args hi you
hi you
bash$ echo $1 $2
one two
bash$
@end example
The @code{set} command is the easiest way to break a multi-word string
into elements that can be referenced individually. This can be useful
in conjunction with command substitution (@pxref{Command Subs}). For
example, we can set the positional parameters to the words in the output
of the @code{date} command as follows:
@example
bash$ set $(date)
bash$ echo $1 $2 $3 $4 $5 $6
Fri Feb 22 18:13:14 EST 1991
@end example
@node Predefined, Command Subs, Positional, Variables
@section Predefined Shell Variables
@c 'predefined shell vars' sound to me like ordinary vars that are defined
@c by the shell (e.g. HOME)
@c bfox: not standard terminology -- can change
@cindex shell variables, predefined
@cindex variables, predefined shell
The predefined shell variables are set by the shell.
You cannot assign them values, but
you can reference their values by prefacing their names by @samp{$}.
The predefined shell variables are:
@table @code
@item ?
contains the exit status returned by the command that was last run in
the foreground.
@item !
contains the process identification number of the last background
command.
@item $
contains the process identification number of the current shell.
@item #
contains the current number of positional parameters (@pxref{Positional}).
@item -
contains shell options.
@c bfox: echo $- gives the options you invoked bash with (as modified by
@c set) [some subset of options -- due to new -o option]
@item 0
(zero) contains the name of the command being executed.
@item *
@itemx @@
contain a list of the positional parameters.
@c bfox:
@code{*} and @code{@@} are equivalent unless they appear
inside double quotes.
@samp{$*} @samp{$@@} are both equivalent to @samp{$1 $2 ... $@var{n}},
where @var{n} is the last positional parameter.
But @code{"$*"} is equivalent to @samp{"$1 $2 $3 @dots{}"}
and @code{"$@@"} is equivalent to @code{"$1" "$2" "$3" @dots{}}.
In other words, @code{"$*"} expands to a single word, whereas
@code{"$@@"} expands to separate words.
@c replace example
@c bfox will suppply example with FOR command
@example
bash$ cat a
this is a file named a
bash$ cat b
this is a file named b
bash$ cat c1
/bin/cat "$*"
bash$ cat c2
/bin/cat "$@@"
bash$ c1 a b
a b: No such file or directory
bash$ c2 a b
this is a file named a
this is a file named b
@end example
@noindent
This example shows the use of two scripts: @code{c1}, which tries to execute
@file{/bin/cat} on the expansion of @samp{$*}, and @code{c2}, which executes
@file{/bin/cat} on the expansion of @samp{$@@}. When invoked with more
than one argument, @code{c1} attempts to run @code{cat} on the file whose name
is the concatenation all its arguments -- not what you would expect.
On the other hand, @code{c2} uses @samp{$@@} and behaves correctly.
@end table
The following example sets the positional parameters to
the output of the @code{date} command and shows that that output
consists of 6 words:
@example
bash$ echo $#
0
bash$ set $(date)
bash$ echo $#
6
bash$ echo $*
Sat Aug 4 22:19:05 EDT 1990
@end example
Here's an obscure script using predefined parameters:
@example
#
# 2, 3, 4, 5 -- print in the number of columns defined by the
# name of the script. Adapted from Kernighan and Pike.
#
/bin/pr -$(basename $0) -t -l1 "$@@"
@end example
@noindent
This file prints its input in as many columns as specified by its
name -- if invoked as "2", it prints its input in two columns.
@node Parameter Subs, Arithmetic Evaluation, Command Subs, Variables
@section Variable Substitution
@c Posix has excellent description of this, with table comparing the
@c different substitutions. Plagiarize it.
The simplest case of @dfn{variable substitution} is the simple
@code{$@var{name}} construct, in which the value of the variable
@var{name} is substituted for @code{$@var{name}}.
More complicated constructs let you specify what should happen
if the named variable is unset or if its value is null.
@cindex parameter substitution
@cindex substitution, of parameter values
BASH's parameter substitution facility lets you test and conditionally set the
value of parameters and shell variables.
@c what's param vs. shell var
Braces allow a variable to be
tested to see if it is defined and is not the null string. This is
important as sometimes the value of an expression depends on whether or
not a variable has been defined. If the colon in the following
expansions is omitted, BASH only tests that the parameter is
unset; it does not test to see that it's unset or null.
The substitutions allowed are:
@c fix up items below to make differences clear by using a single
@c example throughout
@table @code
@item $@{@var{variable}@}
The value of @var{variable} is substituted. The braces are required
when @var{variable} is a positional parameter with more than one digit,
or when @var{variable} is followed by a character that isn't part of
its name.
@c e.g. ${v}e -- why should that happen?
@item $@{@var{variable}:-@var{string}@}
If the named @var{variable} exists, then the expression has
the value of the variable, otherwise it has the value @var{string}.
For example:
@example
echo $@{timenow-$(date)@}
@end example
@noindent
This echoes the current time, as stored in the variable @code{timenow}.
If @code{timenow} isn't set, the @code{date} command is run to generate
it.
@c clarify -- date generates time, doesn't set timenow var
@item $@{@var{variable}:=@var{string}@}
If the named @var{variable} exists, then the expression has
the value of the variable, otherwise it has the value of @var{string}
@emph{and} @var{string} is assigned to @var{variable}. For example:
@example
bash$ echo $A
bash$ echo $@{A=123@}
123
bash$ echo $A
123
@end example
@noindent
The first line of this example shows that @samp{A} is unset.
@c actually, nset or null
The second line assigns the value of 123 to @samp{A}. Then the value of
@samp{$A} is substituted, so @samp{A} retains the value 123.
@c last sentence unclear
This form does not work with positional parameters (@pxref{Positional})
or special parameters (@pxref{Predefined}).
@c what doesn't work? just this := case? unlikely
@item $@{@var{variable}:+@var{string}@}
If the named @var{variable} exists, then it has
@c has --> gets?
the value of @var{string}, otherwise it has no value.
@c ? otherwise not created?
For example:
@example
if [ "$@{var+set@}" = "set" ] ; then
echo '$var' is set
fi
@end example
@noindent
This example shows a simple method to test whether or not a shell
variable is set. If @code{var} has a value, then the expansion has the
value @code{set}, and you can test on that fact.
@c expansion? test?
@item $@{@var{variable}:?@var{text}@}
If the named @var{variable} exists, then the expression has
the value of the variable, otherwise the message @var{text} is printed.
For example:
@example
: $@{REQUIRED?"REQUIRED must be set"@}
@end example
@c example messed up? colon in wrong place?
@noindent
This statement echoes @samp{REQUIRED must be set} if @code{REQUIRED} is not set.
This can be used to inform the user that further execution of the
current script is not possible. If you don't make this part of an
interactive script, the shell exits after printing the
message.
@c ???
If there is no @var{text} following the @samp{?}, BASH prints a standard
message.
@item $@{#@var{variable}@}
The length in characters of the value of @var{variable} is substituted.
@c next sentence ???
If @var{variable} is @samp{*} or @samp{@@}, the length substituted is
the length of @samp{*} expanded within double quotes.
@item $@{@var{variable}#@var{string}@}
@itemx $@{@var{variable}##@var{string}@}
@c ???
The @var{string} is expanded to produce a pattern just like pathname
expansion. If the pattern matches the beginning of the value of
@var{variable}, then the expansion is the value of @var{variable} with
the shortest matching pattern deleted (the @samp{#} case) or the
longest matching pattern deleted (the @samp{##} case).
@item $@{@var{variable}%@var{string}@}
@itemx $@{@var{variable}%%@var{string}@}
@c ???
The @var{string} is expanded to produce a pattern like pathname
expansion.@c ???
If the pattern matches
@c matches ???
a trailing portion of the value of
@var{variable}, then the expansion is the value of @var{variable} with
the shortest matching pattern deleted (the @samp{%} case) or the longest
matching pattern deleted (the @samp{%%} case).
@end table
@node Functions, Programming, Aliases, Top
@chapter Shell Functions
@cindex functions
@c need to say what functions are for
A shell function stores a series of commands for execution at a later
time, similar to a shell script. Functions are executed in
the current shell; no new process is created to interpret them.
@node Function Definition
@section Defining a Function
@c fix: fn def is a cmd, can go anywhere
Function definitions can be entered from the command line or declared in
your login file (@pxref{Start-up}).
The shell doesn't save functions when you log off. To make
function definitions ``permanent'' you must enter them in your login file
(@pxref{Start-up}).
To declare a function use either of the following equivalent forms:
@cindex functions, format of
@c ? what's the format of the list? what's a legal name? same as var
@c names except fn name can contain dash in addition to what var name can have
@example
function @var{fname} () @{ @var{commands} @}
@r{or}
@var{fname} () @{ @var{commands} @}
@end example
@noindent
It makes no difference which form you use. Both create a simple
command invoked by @var{fname} which executes the given @var{commands}.
@cindex functions, recursive
@cindex recursive functions
A function can be recursive; that is, it can call itself. No limit is
imposed on the number of recursive calls that can be made. However,
make sure you put in checks to avoid infinite recursion, as you would
in any programming language.
@node Function Arguments
@subsection Function Arguments
@cindex functions, positional parameters and
@cindex positional parameters, functions and
Arguments present on the command line along with @var{fname} are passed
to the function as positional parameters during its execution
(@pxref{Positional}). The special parameter @code{#} is updated to
reflect the change. Positional parameter @code{0} is unchanged. When the
function finishes, the values of the positional parameters and the
special parameter @code{#} are restored to the values they had before
the function was executed.
Here's an example of a function, using the first syntax:
@c ? how about a simpler, more basic example?
@example
function xtitle()
@{
if [ "$DISPLAY" ] ; then
echo -n -e "\033]2;$*\007";
echo -n -e "\033]1;$*\007";
fi
@}
@end example
@noindent
@c ?
If BASH is executing in an xterm window,
@c what's an xterm window?
this function makes its arguments
@c whose args? the fn?
be the string displayed in an xterm title bar.
@c use same example both times (above & here)
Here's an example of a function, using the second syntax:
@c ? another mysterious example
@example
cd()
@{
builtin cd "$@@" &&
xtitle $HOST: $PWD
@}
@end example
@noindent
This redefines the @code{cd} built-in command to allow setting the
title of an xterm window to the host name and current directory.
@cindex functions, the shell and
@cindex functions, execution of a
@cindex functions, making permanent
@c ? call vs. execute vs. interpret (call is defined in next section)
Shell functions can be executed only in the same shell that
is used to call that function. The shell does not fork a copy of
itself
@c ? fork a copy?? and isn't subshell for a script optional?
to interpret the function, like it would with a script.
@menu
* Listing:: Listing available functions.
* Calling:: Calling functions.
* Export:: Exporting functions.
* Local:: Local variables within functions.
* Return:: Returning from function calls.
@end menu
@node Local, Return, Export, Functions
@subsection Local Variables
@cindex local variables, functions and
@cindex @code{local} command
@cindex functions, local variables and
@cindex functions, @code{local} command and
Bash supports the use of local variables within a function.
A local variable shadows the value of a previously defined variable
(local or not) with the same name.
Local variables differ from other variables in only one way: when the
function that defined the variable exits, the local variable goes away,
and any previously defined variable with the same name becomes visible
again.
There is no way to have changes made to a local variable affect the
value of any previous variable with the same name. Local variables
have to be exported to be available to programs invoked by that
function, and to their children, too.
@c children not explained
Local variables are created with the @code{declare} or @code{local}
commands (@pxref{Built-in}):
@table @code
@c KELLEM added i (frxi)
@item declare @r{[}-+frxi@r{]} @r{[}@var{name}@r{[}=@var{value}@r{]}@r{]}
This command declares variables and gives them attributes. If no
@var{name} is given, then a listing of the values of variables is
displayed, instead.
The @samp{-f} option causes @code{declare} to use function names only.
@c ? only as opposed to what?
The @samp{-r} option causes @code{declare} to make @var{name} readonly.
@c ? what's readonly?
The @samp{-x} option causes @code{declare} to make @var{name} export
only.
@c ? what's export only?
@samp{+} and @samp{-} turn on and off, respectively, the options.
@c ? on/off unclear
When @code{declare} is used in a function, it makes @var{name} local,
the same as the @code{local} command.
@example
bash$ type z
z is a function
z ()
@{
declare a=2;
echo in z, a = $a;
@}
bash$ a=3
bash$ z
in z, a = 2
bash$ echo $a
3
@end example
@noindent
The instance of the variable @code{a} in the function @code{z} is
private to @code{z}; the value of @code{a} in the shell
(set by @samp{a=3)} does not
affect it and is not affected by it (as shown by the final @samp{echo $a}).
@item local @var{name}@r{[}=@var{value}@r{]}
This creates a local variable called @var{name}, and gives it a value
of @var{value}. The @code{local} command can be used only within a
function; it causes the variable @var{name} to be restricted to that
function and its children.
@c ? what children?
@example
bash$ type z
z is a function
z ()
@{
local pid=$$;
@c ? what's $$
echo This function is executed in shell $pid;
@}
bash$ echo $pid
bash$ z
This function is executed in shell 252
bash$ echo $pid
bash$
@end example
@noindent
The variable @code{pid} is private to function @code{z}; the calling
shell has no such variable.
@c echo above doesn't tell us there's no such var, just that either
@c there's no such var or there's such a var with a null value
@end table
Here is the declaration of a function that uses a local version of the
@code{PATH} variable, and executes all of its arguments using a
@code{PATH} which contains only @file{/bin}:
@example
using_bin () @{
local PATH=/bin
eval $*
@}
@end example
@noindent
A useful call to this function might look like:
@example
using_bin "rm *.texinfo; cp ../*.texinfo ."
@end example
@c ? what are the quotes for? to have just 1 arg? why not do w 2 args?
@node Return, , Local, Functions
@subsection Returning From Functions
@cindex functions, return status
@cindex @code{return} command
@cindex functions, @code{return} command and
A function exits if an error occurs, if a @code{return} statement is
executed, or after executing the last command.
Here is the syntax of the return command:
@example
return @r{[}@var{n}@r{]}
@end example
@noindent
@c ? return status (= return value ?) not defined -- = exit status?
This causes a function to exit with the return value specified by
@var{n}, if present. If @var{n} is omitted, the return status is that
of the last command.
Here's an example:
@example
true()
@{
return 0
@}
false()
@{
return 1
@}
@end example
@noindent
These are replacements for the commands of the same name, and will
execute much faster.
@c ? what true/false cmds? documented? what are they for? Why is this faster?
@node Calling, Export, Listing, Functions
@section Calling Functions
@cindex functions, calling
To use a function you must @dfn{call} it. This works the same way as
calling (and using) any program. Here is the syntax used to call a
function:
@example
@var{fname} @r{[} @var{args} @r{]}
@end example
@noindent
This calls the function named @var{fname}, and provides it with
optional command-line arguments, @var{args}. Here's an example:
@example
bash$ f /usr/spool/mail/close
@end example
@noindent
This calls the function @code{f} with the name of a system mailbox as
its argument. In the body of the function, @samp{$1} is replaced with
@file{/usr/spool/mail/close}.
@cindex functions, operating system commands and
@cindex operating system commands and functions
@cindex functions, the @code{command} command and
@cindex @code{command} command
If you have a function with the same name as an operating system
command, you can do one of two things to be able to run that operating
system command instead of your function. You can call the command using its full pathname, or
you can use the @code{command} command (@pxref{Built-in}):
@example
command @r{[}@var{command} @r{[}@var{args}@r{]}@r{]}
@end example
@noindent
This causes the shell to run the command named in @var{command} with
the arguments specified by @var{args}, ignoring shell
functions. For example, if you have a shell function called @code{ls},
and you want to run the operating system's @code{ls} command instead,
you'd have to say @samp{command ls}.
@node Listing, Calling, Functions, Functions
@section Listing Available Functions
@cindex functions, listing
You can get a list of all the currently defined functions using the
@samp{-f} option of the @code{declare} command (@pxref{Built-in}). The
text of the functions, as well as the function names, is included in
the listing. For example:
@example
bash$ declare -f
declare -f f ()
@{
grep "^From:" $@{1-$MAIL@};
@}
declare -f popd ()
@{
builtin popd "$@@";
xtitle $HOST: $PWD;
@}
declare -f pushd ()
@{
builtin pushd "$@@";
xtitle $HOST: $PWD;
@}
declare -f cd ()
@{
builtin cd "$@@";
xtitle $HOST: $PWD;
@}
declare -f xtitle ()
@{
echo -n -e "\033]2;$*\007";
echo -n -e "\033]1;$*\007";
@}
@end example
@noindent
This lists the names of the functions together with their definitions.
@node Environment, Conditionals, Variables, Top
@chapter The Shell Environment
@c should precede or merge with shell var chapter?
@c ? documentation of export and declare is very inconsistent, over the
@c parts of this chapter and the built-in command appendix.
@c What are they supposed to do? In particular, is it supposed to be
@c the case that:
@c export = declare (or maybe declare -x)
@c export -f = declare -f (or maybe declare -fx)
@c Is export intended to replace declare ?
@c cover 'set -o allexport...' somewhere in this chapter
@cindex environment
@cindex shell environment
@c ? program environment vs. shell environment
When a program is invoked it is given an array of strings called the
@dfn{environment}. The shell @dfn{environment} is the set of all
shared and exported
@c ? shared = exported?
shell variables and functions. By typing
@code{declare -x}, or the @code{export} command by itself, you can see
a list of all exported variables. This is a list of name-value pairs,
of the form @samp{@var{name}=@var{value}}:
@example
bash$ export
declare -x HOME=/usr/chet
declare -x SHELL=/bin/bash
declare -x TERM=xterm
declare -x USER=chet
declare -x PATH=/usr/local/bin/gnu:/usr/local/bin:/usr/ucb:/bin:/usr/bin
declare -x HOSTTYPE=IBMRT
declare -x MAILCHECK=60
declare -x BASH=/bin/bash
declare -x HISTFILE=/usr/chet/.history
declare -x HISTSIZE=500
declare -x LOGNAME=chet
declare -x TZ=EST5EDT
declare -x MAIL=/usr/chet/mbox
declare -x HOST=arrakis
declare -x EDITOR=/usr/local/bin/ce
declare -x VISUAL=/usr/local/bin/ce
declare -x PAGER=/usr/local/bin/more
declare -x DISPLAY=unix:0.0
@end example
A process can access and use any environment variables and functions
that exist in that process's environment.
@c ? access AND use?
C programs have a @code{getenv()} function available for this purpose.
@c sudden switch from 'commands' (scripts, etc.) to C progs
The shell allows you to manipulate the environment in several ways. On
invocation,
@c clarify 'invocation' -- maybe ``when it starts up, the shell scans...''
the shell scans its own environment and creates a parameter
@c ? parameter?
for each name found, automatically marking it for export to child
processes.
@c ? marking paramater? marking name?
Generally, this ``basic'' environment consists of (at least) the
@code{HOME}, @code{PATH} and @code{TERM} variables. These tell the
shell what your home directory is, the search paths you use most often,
and what terminal you want to emulate, respectively. Other variables
are used to customize your environment to make it more
useful to you.
Executed commands inherit this environment.
@c ? what environment?
@c ? explain inherit. different from share? use?
If the value of a parameter
@c ? parameter
in the environment is modified,
@c ? modified by the command that's executed?
the new value becomes part of the environment, replacing the old.
@c ? doesn't subshell have COPY of env?
@c ???
Therefore, the environment inherited by any executed command consists
of the shell's initial environment, whose values may be modified in the
shell, less any values removed by the @code{unset} command, plus any
additions via the @code{export} and @code{declare} commands.
@c ??? child processs? subshells?
Remember that exported variables can only be exported to child
processes. If you want to make a variable accessible to all subshells,
be sure to define and export it in your login shell.
The environment for any simple command or function can be augmented
temporarily by prefixing the command with parameter assignments.
@c ? parameter = shell variable ?
These assignment statements affect only the environment seen by that command.
@example
bash$ foo=bar printenv foo
bar
bash$ printenv foo
bash$
@end example
@c ???
If @samp{set -k}
@c substitute new 'set -o ...' version of above
is used (@pxref{Built-in}), then all parameter
assignments are placed in the environment for a command, not just those
that precede the command name.
@node Shared Variables, , Arithmetic Evaluation, Variables
@section Shared Variables
@c ? shared = exported?
@cindex shared variables
@cindex local variables
@cindex variables, local
@cindex variable, shared
@cindex shell variables, local
@cindex shell variables, shared
Normally shell variables are @dfn{local} variables. That is, these
variables are known only to the shell that created them. When you
start a new shell (@pxref{Install}), the new shell doesn't know about
any of the old shell's variables. Each shell's variables are known
only (are local) to itself.
Sometimes, however, we want a new shell to recognize the old
shell's variables. You can accomplish this using the @code{export}
command (@pxref{Built-in}):
@table @code
@item export @var{names}
exports the value of named variables @var{names} to a subshell.
@c what subshell?
Exported variables can only be exported
to child processes and @emph{not} back to parent processes.
@c to every child created from now on?
@c explain child & parent somehwere
@item export -n @var{names}
removes the export property from the named variables, @var{names}.
@c i.e. no longer exported?
@item export
lists the variables that are already exported.
@c ? relationship to declare -x ?
@end table
The @code{export} command actually gives only a @emph{copy} of the
original variable to the new subshell. When the subshell dies, so does
the value of the variable @emph{copy}; the original variable value
remains untouched.
@c key is probably that changes to var in subshell don't affect value
@c seen by parent shell ?
@node Export, Local, Calling, Functions
@section Exporting Functions
@cindex functions, exporting
@cindex @code{declare} command
@cindex functions, @code{declare} command and
@cindex @code{export} command
@cindex functions, @code{export} command and
Normally, functions are unset
@c ? unset?
when the shell executes a shell script.
You can get around this problem by exporting your functions to the
environment (@pxref{Environment}). Exported functions are available to
any invocation of the shell, including any shell scripts. There are
two ways you can export functions: use the @samp{-f} option of the
@code{export} command or use the @samp{-xf} option of the
@code{declare} command (@pxref{Built-in}). Here's how they work:@refill
@c ? why synonymous commands?
@c confusing: export -f fn = declare -xf fn, export -f = declare ??
@table @code
@item export -f @var{fname}
exports the function named @var{fname} to the environment. More
than one function name can be listed for export.
@item export -f
lists the currently exported functions.
@noindent
For example:
@c ? what is 'type'
@example
bash$ type fn
fn is a function
fn ()
@{
grep "^From:" $@{1-$MAIL@};
@}
bash$ export -f fn
bash$ export -f
declare -xf fn ()
@{
grep "^From:" $@{1-$MAIL@};
@}
@end example
@item declare -xf @var{fname}
exports the function named @var{fname} to the environment. More
than one function name can be listed for export.
@item declare -xf
lists the currently exported functions.
@c ? is it declare -xf or declare -x? example below confused
@noindent
For example:
@example
bash$ type fn
fn is a function
fn ()
@{
grep "^From:" $@{1-$MAIL@};
@}
bash$ declare -x fn
bash$ declare -xf
declare -xf fn ()
@{
grep "^From:" $@{1-$MAIL@};
@}
@end example
@noindent
The first @code{declare} statement marks the function @code{fn} for
export to the environment.
@c ? marks for export = exports (above) ?
The second statement lists all exported
functions; in this case @code{fn} is the only one.@refill
@end table
@node Substitution
@chapter Command Substitution and Arithmetic Evaluation
@node Command Subs, Parameter Subs, Predefined, Variables
@section Command Substitution
@cindex command substitution
@cindex substitution, of command values
A command enclosed in backquotes,
@samp{`@var{command}`}, is replaced by the output it
produces. This is called @dfn{command substitution}.
For example:
@example
bash$ echo I am logged in as `whoami`
I am logged in as jems
bash$
@end example
@noindent
Inside single quotes, a backslash retains its literal meaning, except when followed by
a @samp{$}, @samp{`}, or a @samp{\}.
@c ? what happens in those cases? why just those cases?
@c preferred syntax should be first, other mentioned as historical
You can also perform command substitution using the
@samp{$(@var{command})} syntax.
This is the preferred syntax for command substitution.
When this form of command substitution
is used, none of the characters between the parentheses are treated
specially; all characters are considered to make up the command.
Here's an example:@refill
@c candidate for world's worst example?
@example
kill -1 $(cat /etc/named.pid)
@end example
@noindent
This sends a hangup signal (@code{SIGHUP}) to the process whose process
@sc{id} is in the file @file{/etc/named.pid}.
Note that the command substitution operation replaces any linefeed
characters in the command's output with space characters.
@c ? linefeed = newline?
The shell also deletes trailing newlines.
@c what's word splitting? path name expansion?
Note, also, that word
splitting and path name expansion are not performed on the resulting
command if the substitution appears within double quotes.
@c ??? what substitutiont? what resulting command?
Command substitutions may be nested. (When nesting using the
@samp{`@var{command}`} form, protect the inner backquotes with
backslashes to prevent shell misinterpretation.)
Command substitution is useful in assigning variables. Use it when you
want the output of a command to be the value of a variable. For
example:
@example
x=$(pwd)
@end example
@noindent
This assigns @code{x} the value of your current working directory. This
example isn't really useful because shell has built-in command
(@code{cd}) for performing this action.
@c ? huh? cd doesn't assign x
Here's a more useful example:
@example
i=$(expr $i + 1)
@end example
@c ? what's expr?
@noindent
This increments a number if @var{i} is a number. This is useful in
shell scripts for creating loops.
Here's another example:
@example
name=$(basename $i)
@end example
@noindent
This removes all the path information from @var{$i} and gives you a
pure file name.
A common use of command substitution's linefeed-to-spaces translation
is keeping lists of items on separate lines of a file, and then using
@code{cat} inside of back-quotes to produce word lists for the
@code{for} command (@pxref{for}).
In the following example, the @code{cat} command is used to write the
contents of file @file{namelist} to the output:@refill
@example
bash$ cat namelist
joe
sam
mary
ezekiel
bash$ echo `cat namelist`
joe sam mary ezekiel
@end example
Here's an example using the file
@file{namelist} from above:@refill
@example
bash$ for i in `cat namelist`
bash> do
bash> echo "Hi there, $i."
bash> done
Hi there, joe.
Hi there, sam.
Hi there, mary.
Hi there, ezekiel.
@end example
@c KELLEM added this skeletal section
@c this section assumes that $[..] arithmetic evaluation is included in
@c 1.06 -- it's from posix and should be included
@node Arithmetic Evaluation, Shared Variables, Parameter Subs, Variables
@section Arithmetic Evaluation
@c this section should probably be reworded a little, but it's a start
@cindex arithmetic evaluation
@cindex arithmetic expressions
@cindex expressions, arithmetic
@cindex evaluating arithmetic expressions
@cindex math expressions
You can evaluate arithmetic expressions in BASH. The syntax for
arithmetic evaluation is @samp{$[@var{expression}]}. The
@var{expression} is treated as if it were within double quotes, but a
double quote inside the brackets is not treated specially. All tokens
in the @var{expression} undergo parameter expansion, command
substitution, and quote removal. Arithmetic evaluations may be
nested.@refill
The evaluation of expressions is done in long integers with no check for
overflow, though division by 0 is trapped and flagged as an error. The
following list of operators is grouped into levels of equal precedence
operators. The levels are listed in order of decreasing precedence.
@table @code
@item -
unary minus
@item !
logical @sc{not}
@item * / %
multiplication, division, remainder (modulus)
@item + -
addition, substraction
@item <= >= < >
comparison operators
@item == !=
equality, inequality
@item =
assignment
@end table
Shell variables are allowed as operands; parameter expansion is
performed before the expression is evaluated. The value of a parameter
is coerced to a long integer within an expression. Operators are
evaluated in order of precedence. Subexpressions in parentheses are
evaluated first and may override the precedence rules above. Operators
of equal precedence are evaluated from left to right.
You may also specify arithmetic evaluation with the @code{let} builtin
command. @xref{Built-in, let, Builtin Commands}, for more
information.@refill
@node Scripts, Variables, Programming, Top
@chapter Shell Scripts
@cindex shell scripts
@cindex scripts
A shell script is a collection of operating system commands,
comments, and shell programming-language constructs grouped together in
a file.
Shell scripts can be composed of fixed commands requiring no arguments,
and run without interruption. Scripts can also be composed of commands
that require user input. If this is the case, the script can obtain
that input either by prompting or by arguments included on the command
line used to invoke the script. Scripts can also use pipes and
redirection both internally and externally.
@c ? what does last sentence mean?
@c guess: internal = redir ops in cmds in script, external = i/o of
@c script redirected by command invoking script
@cindex script, how to execute a
You can run shell scripts in a number of ways. You can type the
@code{bash} command followed by the script file name, or you can turn the
script into an actual command using the @code{chmod} command
(@pxref{chmod, , @code{chmod}, utilities, The GNU Utilities Manual}),
and execute that new command by typing the script's file name. Both of
the ways of executing a script create a new shell process.
@c ? last sentence false? surely bash foo runs foo in a fresh bash,
@c (actually, I don't see it doc'ed like this)
@c but foo creates a foo (non-shell) process
@c must explain shell process above, & current/new process below
To execute a program without creating a new process you can use the
@code{.} command or the @code{source} command (@pxref{Built-in}). These
execute a shell script as part of the current process. Each line in the
script is acted upon as if you had typed it, excepting that the shell's
notion of interactiveness is turned off.
The @code{exec} command
(@pxref{exec, , @code{exec}, utilities, The GNU Utilities Manual}),
also executes programs in
place of the current process, but @code{exec} never returns control to
the original program.
@cindex script, steps in writing a
To summarize, here's one of the easiest ways of writing and executing a
shell script:
@c it's not a summary, it's new info
@c (above, needed exec, ., or source -- chmod case wasn't clear
@enumerate
@item
Create a file that contains the commands you want to execute. For
example, a series of commands that you execute frequently and are tired
of repeatedly typing.
@item
Change the file access mode so the file can be run like a program
rather than be treated like a data file. For example, @code{chmod +rx
@var{file}}, where @var{file} represents the name of your script. The
@samp{+rx} option allows all users to read and execute this file.
@c ? why do all users? for just me, do +x ?
@item
Type the name of the file to execute the commands in the shell script.
@end enumerate
@cindex script, sample of
Here's an example of a simple shell script:
@example
#Display the date, time, username and current directory.
echo "The current date and time is:"
date
echo " "
echo "You are `whoami` \n" #print username.
echo "Your current directory is `pwd`." #print current directory.
@end example
@noindent
This script prints the current date, time, username and working
directory for the user who invokes it. The first line of this script
is a comment, identified by the pound sign @samp{#} that begins it.
Comment statements don't get executed; use them to
document your shell script.
Notice that comments don't have to be placed on a line by themselves.
When a word begins with a @samp{#} sign, it causes the rest of that
line to be interpreted as a comment, and not executed.
Note: @samp{#} works only in a noninteractive shell.
@c new concept: [non]interactive shell
@cindex command lines, comments in
@cindex comments
@cindex scripts, comments in
@cindex non-interactive shells, comments in
The backquotes around the @code{whoami} and @code{pwd} commands shows
the use of command substitution (@pxref{Command Subs}). Basically
@c ? basically
the shell replaces the command (including the backquotes) with the
output of that command. The @samp{\n} tells @code{echo} to add an extra
carriage return to the end of the line.
@xref{Advanced Scripts}, for more advanced examples of writing scripts.
@node Conditionals and Loops, Built-in, Environment, Top
@chapter Conditionals and Loops
@c Intro not related to rest of chapter.
@c Rest of chapter isn't about shell use of exit status.
@cindex conditional statements
BASH has some built-in decision-making and looping statements. Most of these
statements base their decisions on the @dfn{exit}, or @dfn{return},
status of specified processes. An exit status is simply a flag that
indicates the success or failure of an executed command.
@c what's a flag? a value?
Exit status flags are returned to the parent process when a child
process stops executing (for any reason).
For example, suppose we wish to look at the contents of a file using
the @code{cat} command. If the specified file cannot be found, it
certainly can't be looked at and the attempt to execute @code{cat} is
looked upon as unsuccessful by the shell. Therefore the exit status is
returned as ``unsuccessful''.
This status can be tested by the shell and used to make decisions about
what actions to take next. An exit status of zero means that the
command was executed successfully. An exit status of non-zero means
that the command was unsuccessful.
@menu
* if:: The @code{if} statement.
* case:: The @code{case} statement.
* for:: The @code{for} statement.
* while:: The @code{while} statement.
* until:: The @code{until} statement.
* break & continue:: The @code{break} statement and the
@code{continue} statement.
@end menu
@node if, case, Conditionals, Conditionals
@section The @code{if} Statement
The syntax of the @code{if} statement is:
@example
if @var{condition}
then
@var{commands}
@r{[}elif @var{condition}
then
@var{commands}@r{]}
@dots{}
@r{[}else
@var{commands}@r{]}
fi
@end example
@noindent
where the brackets and the dots indicate that the @code{else} part is optional
and that there can be any number (including none) of @code{elif} parts.
If the commands contained in the first @var{condition} are successfully
executed, then the commands contained in the first @var{commands} are
executed.
The optional @code{elif} parts allow you to specify
conditions to test (and corresponding commands to execute if
successful) if previous conditions were not successful.
The optional @code{else} part allows you to specify
commands to execute if none of the @var{condition}s are successful.
After the appropriate @var{condition}s are tested
and any appropriate @var{commands} are
executed, control goes to the statement following the @code{fi}.
Here's an example:
@c replace system example by user example
@example
# check to see that we've got sufficient files to bring the
# system up multi-user
for i in /bin/login /etc/getty /etc/passwd ; do
@c what's the next obscure line???
if [ ! -s $@{i@} ]; then
echo "$@{i@}: not present @dots{} Can't come up to multi-user mode."
>/dev/console
/bin/kill 1
fi
done
@end example
@noindent
This is code to execute at the end of the system startup script. It
checks that the necessary files are present to bring the system up to a
multiuser state, and shuts the system down if the files are not
present.
Here's another example:
@example
if [ -f /etc/license ] ; then
PATH=~/bin.vax-ultrix:$PATH
elif [ -f /hp-ux ] ; then
PATH=~/bin.hp-ux:$PATH
elif [ -x /bin/arch ] ; then
if [ $(/bin/arch) = "sun3" ] ; then
PATH=~/bin.sun3:$PATH
else
PATH=~/bin.sparc:$PATH
fi
else
PATH=~/bin.ibm032:$PATH
fi
@end example
@noindent
This code tacks a machine-specific binary directory onto the
front of the @code{PATH} variable. Only one of the @code{then} bodies is executed,
depending upon the machine being used.@refill
If you don't want to put the parts of an @code{if} statement
on separate lines as shown in the syntax, you don't have to.
But if you move one of the keywords (@code{then}, @code{elif},
@code{else}, or @code{fi}) onto the same line as the preceding
@var{condition} or @var{commands}, you must put
a semicolon before it.
In other words, each
@var{condition} or @var{commands} must be followed by a newline
or a @samp{;}.
@c is it allowable to always end with ;, even if newline next?
For example:
@c what is the [...] ?
@c The condition here, with =, is not a case of 'successful execution'
@c as discussed above. Rather, it's a comparison. Confusion of
@c concepts: exit status used as t/f for tests
@example
if [ "X$PS1" = "X" ]; then exit ; else echo "interactive shell" ;
fi@refill
@end example
@noindent
This echoes ``interactive shell'' if BASH is executing interactively.
The variable @code{PS1} is set only if the shell is interactive.
@node case, for, if, Conditionals
@section The @code{case} Statement
The syntax of the @code{case} statement is:
@example
case @var{string} in
@var{pattern_1a} | @var{pattern_1b} | @var{pattern_1c})
@var{commands1}
;;
@var{pattern_2})
@var{commands2}
;;
@dots{}
esac
@end example
This statement tries to match a string, @var{string}, to various
@var{patterns}. If it finds a match, it
executes the corresponding pattern's commands. When execution is
complete, control is transferred to the statement following the
@code{esac}.
Each pattern in a list is separated
from the next by @samp{|}. Patterns can contain the
file-matching wildcards @samp{*}, @samp{?}, or @samp{[ @dots{} ]}
(@pxref{File Names}). A pattern list is ended with a closing
parenthesis (note that there is no matching open parenthesis).@refill
@c so in this case wildcards aren't just for files
You don't have to separate all the parts of the @code{case} statement
on separate lines as shown above.
Any of the newlines can be omitted.
@c put an example case statement here instead of a template
@example
case @var{string} in @var{pattern1a} @r{[}| @var{pattern1b} @dots{}@r{]}) @var{commands} @r{[};; @dots{}@r{]};; esac @refill
@end example
Here's an example:
@c example redefines builtin cd, while also using it?
@c example is teco-like gibberish -- replace &/or explain
@c Want simpler example here -- use this example in customization
@c section for people to copy if they like the behavior.
@example
cd()
@{
builtin cd "$@@" &&
case "$1" in
'')
PS1='$ '
;;
..|*/..)
PS1="$@{PWD##*/@}$ "
;;
*/*)
PS1=$@{$1##*/@}$ "
;;
*)
PS1="$1$ "
;;
esac
@}
@end example
@noindent
This sets your prompt to contain the name of the current directory,
with all path information stripped.
@c example to explain above sentence
This can be used as a
way to reset your primary prompt when you change directories. If you
are in your home directory, via a @code{cd} with no arguments,
@code{PS1} will contain no directory information at all.
@c need example of behavior after doing it:
@c bash$ cd me
@c me$
@node for, while, case, Conditionals
@section The @code{for} Statement
The @code{for} statement executes a sequence of commands once for each
value in a list of items.
The format of the @code{for} statement is:
@example
for @var{name} @r{[}in @var{list}@r{]}
do
@var{commands}
done
@end example
For each element in @var{list}, @var{name} is set to that
element and the @var{commands} are executed.
When you omit the optional @samp{in @var{list}}, it
defaults to @samp{in "$@@"}, so that the loop is executed once for
each of the command line parameters.
Here's an example:
@example
for host
do
echo $host:
rsh $host w
done
@end example
@noindent
This defines a script that runs the @code{w} command remotely on each
host named as an argument.
@c need example of using the script
Here's an example using the @samp{in @var{list}} option:
@example
for file in $(echo *.c)
do
touch $file
done
@end example
@noindent
This updates the timestamp of each file ending in @samp{.c} in the
current directory. This is useful for preparing for a rebuild of a
software system.
The @code{do} and @code{done} mark the beginning and the
end, respectively, of the loop. When the @var{list} is
used up, control is passed to the statement following the @code{done}.
If you don't want to put the parts of a @code{for} statement
on separate lines as shown in the syntax, you don't have to.
But if you move one of the keywords (@code{do} or @code{done})
onto the same line as the preceding
@var{name}, @var{list}, or @var{commands}, you must put
a semicolon before it.
@c is it allowable to always end with ;, even if newline next?
@node while, until, for, Conditionals
@section @code{while} and @code{until} Loops
The format of a @code{while} or @code{until} loop is:
@example
while @var{condition}
@r{[}do
@var{commands}@r{]}
done
@end example
@noindent
or
@example
until @var{condition}
@r{[}do
@var{commands}@r{]}
done
@end example
In a @code{while} loop, the @var{commands} are
repeatedly executed as long as the @var{condition} executes
successfully (returns an exit status of zero).
Before each pass through the loop, @var{condition} is executed. If
@var{condition} returns zero, @var{commands} is executed. Usually
@var{commands} affects the @var{condition} execution in some way so
that it will eventually return non-zero. Otherwise you end up with an
infinite loop.
When the @var{condition} is unsuccessful in executing, control
jumps to the statement following the @code{done}.
In an @code{until} loop, the @var{commands} are
repeatedly executed as long as the @var{condition} fails
execution (returns an exit status of non-zero).
Before each pass through the loop, @var{condition} is executed.
If @var{condition} returns non-zero, @var{commands} is executed.
Usually @var{commands} affects the @var{condition} execution in some
way so that it will eventually return zero. Otherwise you end up with
an infinite loop.
When the @var{condition} is successful in executing, control is
returned to the statement following the @code{done}.
The following example tests the output of the @code{who} command once
each minute until it finds that a user named @samp{chet} has logged in.
@c explain example -- what are who, grep, sleep
@example
until who | grep chet
do
sleep 60
done
@end example
If you don't want to put the parts of a @code{while} or @code{until} statement
on separate lines as shown in the syntax, you don't have to.
But if you move one of the keywords (@code{do}
or @code{done}) onto the same line as the preceding
@var{condition} or @var{commands}, you must put
a semicolon before it.
In other words, the
@var{condition} and @var{commands} must each be followed by a newline
or a @samp{;}.
@c is it allowable to always end with ;, even if newline next?
The @samp{do @var{commands}} is optional. Sometimes just
testing the @var{condition} is enough. For example, here's an
inefficient way of reading the last line of a file:
@c what do you mean by reading? who sees it? where does it go?
@c if it's inefficient, isn't it a bad example?
@c explain: what's exec? what's read?
@example
exec < file
while read variable ; done
@end example
@noindent
The return status of @code{read} is 0 (successful) unless the
end-of-file (@sc{eof}) is
encountered. When the @sc{eof} is encountered, the condition is met and the
usefulness of the statement is finished. No @samp{do @var{commands}} section is needed.
@node break & continue, , until, Conditionals
@section The @code{break} and @code{continue} Statements
@cindex loops, interrupting
@cindex interrupting loops
You can interrupt a @code{for}, @code{while}, or @code{until} loop
using a @code{break} or a @code{continue} statement:
@table @code
@item break @r{[}@var{n}@r{]}
The @code{break} statement stops the execution of the loop and passes
control to the statement following the @code{done} that marks the end of
the loop.
If @var{n} is specified, it tells the shell to break at the @var{n}th
level of the enclosing loop.
@c explain nth level -- nested loops?
Here's an example:
@c what is the : in the while?
@c what are echo, read, [], lpr
@example
while :
do
echo -n "Enter name of file to print [q to quit]: "
read fn
if [ "$fn" = "q" ] ; then
break
fi
lpr $fn
done
@end example
@noindent
This prompts for names of files and prints them, until a @samp{q} is
encountered.
@item continue @r{[}@var{n}@r{]}
The @code{continue} statement transfers control to the loop's
@code{done} statement, which continues execution of the loop. If
@var{n} is specified, it tells the shell to resume computation at the
@var{n}th enclosing loop.
@c explain nth level -- nested loops?
Here's an example:
@c what's [], -d
@example
for dir in $(cat dirlist)
do
if [ -d $dir ] ; then
continue
fi
mkdir $dir
done
@end example
@c weird example. Why wouldn't you write it as
@c 'if NOT exists then @c mkdir'
@c without a Continue?
@noindent
This reads a file containing the names of a list of directories to
create, and creates each one if it does not already exist.
@end table
@node Built-in, Shell Vars, Conditionals, Top
@appendix Built-in Shell Commands
@cindex built-in commands, list of
Some of the commands you may want to run are already part of the shell.
Because of this, no new processes are started in order to run these
built-in commands. Therefore, these built-in commands use less time
than those that aren't built-in.
The following is a list of the built-in commands. Some of these
commands are explained in more detail earlier in this manual.
@c shouldn't all of these be in the manual?
@c This is then just alphabetical summary
You are directed to read the appropriate chapter if you need more information
than is provided here:
@c be sure all descriptions here match those earlier
@table @code
@item :
This command can only expand arguments and perform redirections
and nothing else. It is the shell's ``do nothing'' command. It is
not, however, a useless command. Since the shell is able to scan and
parse the line that follows the colon, this command can be adapted for
many uses.
It can be used as a valid option for a program's conditional statement,
or it can be used to create an infinite (until interrupted) loop.
Here's an example:
@example
# wait for a file to be created, chewing up lots of CPU time
# usage: waitfor filename
#
while [ ! -f "$1" ] ; do
:
done
@end example
You can also use the colon to create comment lines, instead of using
the @samp{#} character (@pxref{Scripts}, for more information).
@c other part of doc said # is for noninteractive shell, : for interactive
@ignore
The @samp{:} command can be adapted to create comment lines in an
interactive shell (@pxref{Built-in}).
@cindex command lines, comments in
@cindex comments
@cindex interactive shells, comments in
@cindex colon (@code{:}) command
@iftex
@cindex : command
@end iftex
@c Can't do @cindex : (: is not valid in index/menu in Info mode)
@c from Bob Chassell: A colon cannot be part of an index
@c entry because a colon is used by Info as the marker between the item
@c name and the node name in the index.
@end ignore
For example:
@example
bash$ echo A bad example > junk
bash$ cat junk
A bad example
bash$ : this is a comment about > junk
bash$ cat junk
bash$
@end example
@noindent
First we create the file called @file{junk}, entering a simple message
into that file. Then we create a comment about our file using the
@samp{:} statement and insert a redirection operator into the sentence.
Normally we'd expect the shell to ignore anything that follows a
comment character. However, the shell is able to parse and interpret
the contents of the line following a colon.
Therefore, the above @samp{:} statement, when scanned by the shell,
causes the file @file{junk} to be opened for output, which removes its
prior contents (@pxref{Redirection}).
@c what happens to rest of : line?
So be careful when using the @samp{:} statement. It can be useful when
used properly; but it can also be dangerous in careless hands.
@c ??? what's an example of proper, useful use?
Don't insert any characters that can be expanded by the shell into a
@samp{:} comment line.
@c ??? what's this expansion stuff above?
It's safest to protect the comment following @samp{:} with single quotes
so that it won't be interpreted by the shell.
@c ??? single quotes are new concept
Make sure that there's a space between the colon and the opening single
quote, though, or the shell could mistake what follows for a command:
@c space/command stuff not explained
@example
bash$ : 'This is a good way to make a comment.'
bash$ :'This is bad.'
:This is bad.: command not found.
@end example
@c why not just use # ?? because not valid in interactive shell?
@item . @var{file}
@itemx source @var{file}
Both commands are used to execute shell programs, without creating a
separate child process. The named file is read and executed in the
current shell environment and control is returned to the current shell.
Since these commands do not create a subshell they can be used to
change the value of a shell variable in the current shell.
@var{file} must have a fully qualified path name in order to be
executed. The @code{PATH} variable is searched for the location of the
named file, otherwise the current directory is searched if no file is
found in @code{PATH}.
Redirection of input and output and other command line arguments are
not permitted when using these commands.
@item alias @r{[}@var{name}@r{[}=@var{value}@r{]} @dots{}@r{]}
An alias is defined for each @var{name} whose @var{value} is given.
@xref{Aliases}, for more information. A trailing space in @var{value}
causes the next word to be checked for alias substitution. If a
@var{name} (without the @samp{=@var{value}} part) is given for which no alias has been defined an error
message is printed.
The @code{alias} command, with no arguments, prints the
list of aliases in the form @samp{@var{name}=@var{value}}
on the standard output.
@item bg @r{[}@var{job_spec}@r{]}
This causes the shell to place the specified job, @var{job_spec}, in
the background, as if it had been started with @samp{&}. @xref{Resuming},
for more information. If @var{job_spec} is not present, the shell's
notion of the current job is used.
@item break @r{[}@var{n}@r{]}
This command exits from an existing @code{for}, @code{while}, or
@code{until} loop. If @var{n} is specified, it tells the shell to
break at the @var{n}th level of the enclosing loop. @var{n}
must be greater than or equal to 1. If @var{n} is greater than the
number of the enclosing loops, all enclosing loops are exited.
@item builtin @r{[}@var{shell-builtin} @r{[}@var{arguments}@r{]}@r{]}
This is used to execute a built-in shell command, passing it
@var{arguments}. This is useful when you wish to rename a
built-in shell command to be a function, but need the functionality of
the built-in command within the function itself. (The built-in @code{cd}
command is commonly redefined this way.)
@item cd @r{[}@var{dir}@r{]}
This command tells the shell to change the current directory to the one
specified by @var{dir}. The variable @code{HOME} contains the default
value of @var{dir}.
The variable @code{CDPATH} defines the search path for the directory
containing @var{dir}. @xref{Predefined}, for more information.
Alternative directory names are separated by a colon, @samp{:}.
A null directory name is considered to be the same as the current
directory. If @var{dir} begins with a forward slash, @samp{/},
then the search path contained in @code{CDPATH} is not used.
@item command @r{[}@var{command} @r{[}@var{arguments}@r{]}@r{]}
This causes the shell to run the [external] command named in @var{command} with
the arguments specified by @var{arguments}, ignoring all
other shell functions.@refill
For example, if you have a shell function called @code{ls}, and you
want to call the command @code{ls} as well, you can say @samp{command ls}.
@item continue @r{[}@var{n}@r{]}
This command tells the shell to resume the next iteration of the
enclosing @code{for}, @code{while}, or @code{until} loop at the
@var{n}th enclosing loop (if @var{n} is specified). @var{n}
must be greater than or equal to 1. If @var{n} is greater than the
number of enclosing loops, the last enclosing loop (the ``top-level''
loop) is resumed.
@c KELLEM added i (frxi)
@item declare @r{[}-+frxi@r{]} @r{[}@var{name}@r{[}=@var{value}@r{]}@r{]}
This command declares variables and gives them attributes. If no
@var{name} is given, then a listing of the values of variables is
displayed instead.
@table @code
@item -f
Use function names only.
@item -r
Make @var{name} readonly. These names cannot be assigned
values by subsequent assignment statements.
@item -x
Make @var{name} export to subsequent commands via the environment.
@c KELLEM added -i:
@c the -i is here if $[..] arithmetic evaluation is put into 1.06
@c it's a posix thing
@item -i
Treat @var{name} as an integer; arithmetic evaluation
(@pxref{Arithmetic Evaluation}) will be performed when the variable is
assigned a value.
@end table
Using @samp{+} instead of @samp{-} turns off the attribute.
When @code{declare} is used in a function, it makes @var{name} local,
the same as the @code{local} command (@pxref{Functions}).
@item dirs
This displays the list of currently remembered directories.
Directories are added to the list with the @code{pushd} command; you
can get back up through the list with the @code{popd} command.
@item echo @r{[}-ne@r{]} @r{[}arguments@r{]}
This displays a prompt or a message on the standard output. It outputs
the @var{arguments}, if supplied, separated by spaces. If the
@samp{-n} option is specified, the trailing newline character is suppressed.@refill
If the @samp{-e} option is given, interpretation of the following
backslash-escaped characters is turned on:
@table @code
@c KELLEM added \a:
@c \a is a ksh-88 thing and should be included in 1.06 as far as I know
@item \a
Alert/bell.
@item \b
Backspace.
@item \c
Suppress trailing newline.
@item \f
Form feed.
@item \n
New line.
@item \r
Carriage return.
@item \t
Horizontal tab.
@item \v
Vertical tab.
@item \@var{NNN}
The character whose @sc{ascii} code is @var{NNN} (octal).
@item \\
Backslash.
@end table
@item enable @r{[}-n@r{]} @r{[}@var{names}@r{]}
This command enables and disables built-in shell commands. This allows
you to use an operating system command which has the same name as a
built-in shell command.
If the @samp{-n} option is used, the named commands, @var{names},
become disabled. Otherwise the named commands are enabled.
For example, to use the @code{test} command found in your path instead
of the built-in shell version, you type @samp{enable -n test}.
@item eval @r{[}@var{arguments}@r{]}
The @var{arguments} are read and concatenated together into a single
command. This ``new'' command is then read and executed by the shell.
@item exec @r{[}@r{[}-@r{]}@var{command} @r{[}@var{arguments}@r{]} @r{]}
If @var{command} is specified, it is executed, replacing this shell,
without creating a new process. The @var{arguments} become arguments
to @var{command}.
If the first argument is @samp{-}, the shell places a dash in the
zeroth argument passed to @var{command} (exactly what a login does).
If the @var{command} can't be executed the shell exits, unless the
shell variable @code{no_exit_on_failed_exec} exists.
If @var{command} is not specified, any redirections present
take effect in the current shell.
@item exit @r{[}@var{n}@r{]}
@itemx bye @r{[}@var{n}@r{]}
This causes the shell to exit with the status specified by @var{n}. If
@var{n} is omitted, the exit status is that of the last command
executed. A trap on the shell variable @code{EXIT} is executed before
the shell terminates.
@item export @r{[}-nf@r{]} @r{[}@var{name}@r{[}=@var{word}@r{]}@r{]}
The @code{export} command exports the value of named variables (or
functions if the @samp{-f} option is specified), @var{name}, to a
subshell.
If no variable names are given, @code{export} displays a list of all
the variables that are already exported. The @samp{-n} option causes
the shell to remove the export property from the named variables.
@item fg @r{[}@var{job_spec}@r{]}
This places the specified job, @var{job_spec}, in the foreground, and
makes it the current job. @xref{Resuming}, for more information. If
@var{job_spec} is not present, the shell's notion of the current job is
used.
@item function @var{name} () @r{[} @var{commands} ; @r{]}
@itemx @var{name} () @r{[} @var{commands} ; @r{]}
This creates a simple command invoked by @var{name} which executes the
named @var{commands} (@pxref{Functions}). Arguments on the
command line along with @var{name} are passed to the function as
@samp{$0 @dots{} $@var{n}} (@pxref{Positional}).
@item hash @r{[}-r@r{]} @r{[}@var{name}@r{]}
For each variable name, @var{name}, the full pathname of the command is
determined and remembered. The @samp{-r} option causes the shell to
forget all remembered locations. With no arguments, @code{hash}
presents information about remembered commands.
@c The 'help' sources should be used to augment/check this doc and vice versa
@c I suspect this doc may have come from those sources
@item help @r{[}@var{pattern}@r{]}
This command displays helpful information about built-in commands. If
a pattern is specified,
@c ? same pattern wildcards as for filenames?
@code{help} gives detailed help on all commands
matching @var{pattern}, otherwise a list of the built-ins is printed.
If @var{pattern} contains only alphanumeric characters (no wildcard
characters, such as @samp{?} and @samp{*}), then a pattern of
@samp{pattern*} if assumed. Therefore, the command @samp{help pw} will
produce help on the @code{pwd} command.
@c note: must enclose pattern in quotes if contains wildcards, else
@c expanded to filenames before help sees it
@item history @r{[}@var{n}@r{]}
@itemx history -rw @r{[}@var{file}@r{]}
@itemx history -s @var{arguments}
The first command displays the history list with line numbers. Lines listed
with a @samp{*} have been modified. If a number @var{n} is specified, only
the last @var{n} lines of the history list are displayed.
The @samp{-w} option means causes the current history file to be
written out. The @samp{-r} option causes the current history file to
be read, instead. If a file name, @var{file}, is given, then that file
is used as a history list. If no file name is given, BASH checks to see
if the variable @code{HISTFILE} is set. The file @file{~/.bash_history}
is used as the history file if the variable @code{HISTFILE} is not set.
@xref{History}, for more information.
The @samp{-s} option performs history substitution on the named
arguments.
@item jobs @r{[}-l@r{]}
This lists the active jobs. The @samp{-l} option causes the list of
process identification numbers to be listed in addition to the normal
information. @xref{Job Control}, for more information.
@item kill @r{[}-@var{sigspec}@r{]} @var{pid}
@itemx kill @r{[}-@var{sigspec}@r{]} @var{job_spec}
@itemx kill -l
This sends the processes named by @var{pid} or @var{job_spec} the
terminate signal, or the signal specified by @var{sigspec}, if
present. Signals are specified either by number or by name.
@c where are the numbers defined? documented?
The @samp{-l} option lists the signal names that can be sent. Typing
@code{kill} alone does nothing. @xref{kill}, for more information.
@c KELLEM added next item (let)
@c `let' is for arith. eval. -- from posix, check if really in final
@c release version of 1.06
@item let @var{expression} @r{[}@var{expression} @dots{}@r{]}
Each @var{expression} is an arithmetic expression to be evaluated
(@pxref{Arithmetic Evaluation}). If the last @var{expression} evaluates
to 0, @code{let} returns 1; otherwise 0 is returned.@refill
@item local @var{name}@r{[}=@var{value}@r{]}
This creates a local variable called @var{name}, and gives it a value
of @var{value}.
When the @code{local} command is used within a function it causes the
variable @var{name} to be restricted to that function and its children.
Otherwise it is equivalent to creating normal variables, as if the
@code{local} command had been omitted.
When used without options, @code{local} gives a list of local variables
on the standard output.
@item logout
This exits a login shell.
@item popd @r{[}+-@var{n}@r{]}
This removes entries from the directory stack. With no arguments, it
removes the top directory from the stack, and changes directories
(@code{cd}) to the new top directory.
The @samp{+@var{n}} option removes the @var{n}th entry (counting from
the left of the list shown by the @code{dirs} command), starting with
zero. For example: @code{popd +0} removes the first directory, while
@code{popd +1} removes the second.
The @samp{-@var{n}} option removes the @var{n}th entry (counting from the
right of the list shown by the @code{dirs} command), starting with
zero. For example: @code{popd -0} removes the last directory, while
@code{popd -1} removes the next to last.
You can see the directory stack with the @code{dirs} command.
If the variable @var{pushd_silent} is not set, and the @code{popd}
command was successful, a @code{dirs} will be performed too.
@item pushd @r{[}@var{dir}@r{]}
@itemx pushd @r{[}+-@var{n}@r{]}
This adds a directory to the top of the directory stack, or rotates the
stack, making the new top of the stack the current working directory.
With no arguments, it exchanges the top two directories.
The @samp{+@var{n}} option rotates the stack so that the @var{n}th
directory (counting from the left of the list shown by the @code{dirs}
command) is at the top.
The @samp{-@var{n}} option rotates the stack so that the @var{n}th
directory (counting from the right of the list shown by the @code{dirs}
command) is at the top.
The @samp{@var{dir}} option adds the directory named by @var{dir} to
the directory stack at the top, making it the new current working
directory.
You can see the directory stack using the @code{dirs} command.
If the variable @var{pushd_silent} is not set, and the @code{pushd}
command was successful, a @code{dirs} will be performed too.
@item read @r{[}@var{names}@r{]}
This reads values from the standard input into various shell
variables. One line is read from the standard input, and the first
word is assigned to the first named variable in @var{names}, the second
word to the second named variable, and so on, with leftover words
assigned to the last named variable.
Only the characters in @code{IFS} are recognized as word delimiters
(@pxref{Predefined}).
@item readonly @r{[}-f@r{]}@r{[}@var{names}@r{]}
The given @var{names} are marked readonly and the values of these
various @var{names} may not be changed by subsequent assignments.
If the @samp{-f} option is given, the functions corresponding to the
@var{names} are marked instead. If no arguments are given, a list of
all read-only names is printed.
@item return @r{[}@var{n}@r{]}
This causes a function to exit with the return value specified by
@var{n}. If @var{n} is omitted, the return status is that of the last
command executed in the function body.
@c ? what about set with no args -- prints list of vars
@item set @r{[}-aefhkntuvxldo@r{]} @r{[}@var{arguments}@r{]}
The @code{set} command sets options for the shell:
@table @code
@item a
This marks variables which are modified or created for export.
@item e
This tells a non-interactive shell to exit immediately if a command
exits with a non-zero status.
@item f
This disables path name expansion.
@item h
This tells the shell to locate and remember function commands as those
functions are defined. Normally, function commands are looked up when
the function is executed.
@item k
This tells the shell to place all keyword arguments in the
command's environment. Normally only those that precede the command
name are placed in the environment for a command.
@item n
This tells the shell to read commands but not execute them. This
may be used to check a shell script for syntax errors, for example.
This option is ignored in interactive shells.
@item t
This tells the shell to exit after reading and executing one command.
@item u
This tells the shell to treat unset variables as an error when
performing substitutions. If a substitution is attempted on an unset
variable, the shell prints an error message. If the shell is
non-interactive, it then exits with a non-zero status.
@item v
This prints shell input lines as they are read.
@item x
This prints the value of @code{PS4} followed by commands and their
arguments as they are executed.
@item l
This saves and restores the bindings of the @var{name} in a @code{for}
command (@pxref{for}).
@item d
This disables the hashing of commands that are looked up for execution.
Normally, commands are remembered in a hash table and, once found, do
not have to be looked up again.
@c `o' option changed
@c writeup supplied by KELLEM for new o and for `H', replacing the old `o' option.
@c ? really true that H is here? that both h and H exist and are different?!?
@c that not all the one-letter options have -o named equivalents?
@item H
This enables the @samp{!} style history substitution (@pxref{History}).
This option is on by default.@refill
@item o @r{[}@var{option-name}@r{]}
The @var{option-name} can be one of the following:
@table @code
@item allexport
Same as @samp{-a}.
@item braceexpand
The shell will enable curly brace expansion (SEE BRACE EXPANSION). This
is on by default.
@item emacs
Use an emacs-style command line editing interface
@item errexit
Same as @samp{-e}.
@item histexpand
Same as @samp{-H}.
@item ignoreeof
The effect is as if the shell command @samp{ignoreeof=10} had been
executed (@pxref{Shell Vars, ignoreeof, Shell Variables}).
@item monitor
Same as @samp{-m}.
@c ? no -m doc'ed above
@item noclobber
The effect is as if the shell command @samp{noclobber=} had been
executed (@pxref{Shell Vars, noclobber, Shell Variables}).
@item noexec
Same as @samp{-n}.
@item noglob
Same as @samp{-f}.
@item nohash
Same as @samp{-d}.
@item notify
The effect is as if the shell command @samp{notify=} had been executed
(@pxref{Shell Vars, notify, Shell Variables}).
@item nounset
Same as @samp{-u}.
@item verbose
Same as @samp{-v}.
@item vi
Use a @sc{vi}-style command line editing interface.
@item xtrace
Same as @samp{-x}.
@end table
If no @var{option-name} is supplied, the values of the current options
are printed.
@end table
@c KELLEM interchanged - and + below (so that - is on)
You can turn these options on and off by preceding the option letter
with @samp{-} for on, and @samp{+} for off. You can also set these
options on the command line that invokes the shell. For example:
@example
bash$ bash -v
@end example
@noindent
The special shell variable, @samp{$-} lists the currently defined shell
options.
You can also use the @code{set} command to assign values to positional
parameters (@pxref{Parameter Subs}):
@example
set test junk
@end example
@noindent
sets the positional parameter @samp{$1} to test and @samp{$2} to junk.
The @var{arguments} are passed as positional parameters @samp{$1} to
@samp{$N}.
If you type the @code{set} command alone, with no arguments, you get a
list of all the currently defined shell variables (@pxref{Variables}).
@item shift @r{[}@var{n}@r{]}
This causes the positional parameters from @samp{$@var{n}+1} on up to
be renamed to @samp{$1}, @samp{$2}, and so on. If
@var{n} is not given, it is assumed to be 1.
@item suspend @r{[}-f@r{]}
This suspends the execution of this shell until it receives a
``resume'' (@code{SIGCONT}) signal. The @samp{-f} option, if specified,
prevents messages about this being a login shell (if it is) and causes
the shell to be suspended quietly anyway.
@item test @r{[}@var{expr}@r{]}
@itemx [@var{expr}]
These test for various conditions named in @var{expr}. They return a
status of of 0 (true) or 1 (false) depending on the evaluation of
@var{expr}.
Expressions can be unary or binary. Unary expressions are often used
to examine the status of a file. You can have string operators and
numeric comparison operators too.
File operators:
@table @code
@item -b @var{file}
This tests that the file @var{file} exists and is a block special file.
@item -c @var{file}
This tests that the file @var{file} exists and is a character special
file.
@item -d @var{file}
This tests that the file @var{file} exists and is a directory.
@item -f @var{file}
This tests that the file @var{file} exists and is not a directory
(tests that it is a plain file).
@item -g @var{file}
This tests that the file @var{file} exists and has the set-group-ID bit
set.
@item -k @var{file}
This tests that the file @var{file} exists and has its ``sticky'' bit
set.
@item -L @var{file}
This tests that the file @var{file} exists and is a symbolic link.
@item -p @var{file}
This tests that the file @var{file} exists and is a named pipe.
@item -r @var{file}
This tests that the file @var{file} is readable by you.
@item -s @var{file}
This tests that the file @var{file} exists and is not empty (has a
non-zero size).
@item -S @var{file}
This tests that the file @var{file} exists and is a socket.
@item -t @r{[}@var{FD}@r{]}
This tests to see if file descriptor @var{FD} is opened on a terminal.
If @var{FD} is omitted, it defaults to 1 (the standard output).@refill
@item -u @var{file}
This tests that the file @var{file} exists and has the set-user-ID bit
set.
@item -w @var{file}
This tests that the file @var{file} exists and is writable by you.
@item -x @var{file}
This test that the file @var{file} exists and is executable by you.
@item -O @var{file}
This tests that the file @var{file} exists and is, effectively, owned
by you.
@item -G @var{file}
This tests that the file @var{file} exists and is owned by the
effective group @sc{id}.
@item @var{file1} -nt @var{file2}
This tests that the files @var{file1} and @var{file2} exist and that
@var{file1} is newer than @var{file2} (according to modification date).
@item @var{file1} -ot @var{file2}
This tests that the files @var{file1} and @var{file2} exist and that
@var{file1} is older than @var{file2} (according to modification date).
@item @var{file1} -ef @var{file2}
This tests that the files @var{file} and @var{file2} exist and that
they have the same device and inode numbers.
@end table
String operators:
@c what strings? variables? variable values?
@table @code
@item -z @var{string}
This tests that @var{string} exists and is empty (of zero length).
@item -l @var{string}
When this is used as an operand to any of the binary arithmetic
operators it returns the length of @var{string}.
@item -n @var{string}
@itemx @var{string}
This tests that @var{string} exists and is not empty (has a non-zero
size).
@item @var{string1} = @var{string2}
This tests that @var{string1} and @var{string2} exist and are equal.
@item @var{string1} != @var{string2}
This tests that @var{string1} and @var{string2} exist are not equal.
@end table
Other operators:
@table @code
@item ! @var{expr}
This tests that @var{expr} exists and is false.
@item @var{expr1} -a @var{expr2}
This tests that @var{expr1} and @var{expr2} exist and are both true.
@item @var{expr1} -o @var{expr2}
This tests that @var{expr1} and @var{expr2} exist and that at least
one of them is true.
@item @var{argument1} @var{op} @var{argument2}
@var{op} represents one of the arithmetic binary operators @code{-eq}
(equals), @code{-ne} (not equals), @code{-lt} (less than), @code{-le}
(less than or equal to), @code{-gt} (greater than), or @code{-ge}
(greater than or equal to).
This tests to see if @var{argument1} and @var{argument2} exist and
also tests if @var{argument1} is equal, not equal, less than, less
than or equal to, greater than, or greater than or equal to
@var{argument2}, depending upon the operator used.
@end table
@item times
This prints the accumulated user and system times for the shell and
for processes started from the shell.
@item trap @r{[}-l@r{]} @r{[}@var{arguments}@r{]} @r{[}@var{sigspec}@r{]}
The command named by @var{arguments} is to be read and executed when
the shell receives the signal(s) specified by @var{sigspec}.
@var{sigspec} is either a signal name in <signal.h>, or a signal
number. The @code{trap} command with no arguments prints the list of
commands associated with each signal number. The @samp{-l} option
causes the shell to print a list of signal names and their
corresponding numbers.
If @var{arguments} is absent, all specified signals are reset to
their original values. If @var{arguments} is the null string, the
signal is ignored by the shell and by the commands it invokes.
If @var{sigspec} is @code{EXIT} (0), the command @var{arguments} is
executed upon exit from the shell.
@item type @r{[}-all@r{]} @r{[}-type | -path@r{]} @r{[}@var{names}@r{]}
@c KELLEM: might also allow `-a',`-t', & `-p' as synonyms in 1.06
@c if so, should document here
This allows you to test to see how each named item, @var{name}, would
be interpreted if used as a command name.
@c this item really screwy. command has ``names'', description has ``name''
If the @samp{-type} option is used, it returns a single word, either
@samp{alias}, @samp{function}, @samp{builtin}, or @samp{file}, if
@var{name} is an alias, shell function, shell builtin, or disk file,
respectively. If the name is not found, nothing is printed.
If the @samp{-path} option is used, @code{type} returns either the name
of the disk file that would be executed, or nothing if @samp{-type}
doesn't return a value of @samp{file}.
If the @samp{-all} option is used, it displays all of the
interpretations of @var{names}. This includes aliases and functions, if
and only if the @samp{-path} option is not also used.@refill
@item ulimit @r{[}-cdfmst @r{[}@var{limit}@r{]}@r{]}
@code{ulimit} provides control over the resources available to processes
started by the shell, on systems that allow such control. If an
option is given, it is interpreted as follows:
@table @code
@item -c
refers to the maximum size of core (memory dump) files created.
@item -d
refers to the maximum size of a process's data segment.
@item -f
refers to the maximum size of files created by the shell.
@item -m
refers to the maximum resident set size.
@item -s
refers to the maximum stack size.
@item -t
refers to the maximum amount of cpu time, in seconds.
@end table
If @var{limit} is given, it represents the new value of the specified
resource. Otherwise, the current value of the specified resource is
printed.
If no options are given, the @samp{-f} is assumed to be active. Values
are in 1k increments, except for @samp{-t}, which is in seconds.
@item umask @r{[}@var{nnn}@r{]}
This sets the user file-creation mask to the octal number @var{nnn}.
If @var{nnn} is omitted, the current value of the mask is printed.
@item unalias @r{[}@var{names}@r{]}
This removes the named alias(es), @var{names}, from the list of defined
aliases.
@item unset @r{[}-f@r{]} @r{[}@var{names}@r{]}
This removes the corresponding variable or function specified by
@var{names}. If the @samp{-f} option is given, then functions are
removed.
The predefined variables @code{PATH}, @code{IFS}, @code{PPID},
@code{PS1}, @code{PS2}, @code{UID}, and @code{EUID} cannot
be unset (@pxref{Shell Vars}).
@item wait @r{[}n@r{]}
This asks the shell to wait for the specified process, @var{n}, and
report its termination status. @var{n} can be a process @sc{id} or a
job specification. If a job specification is given, all processes
in that job's pipeline are waited for.
If @var{n} is not given, all currently active child processes are
waited for, and the return code is zero. @xref{wait}, for more
information.
@end table
@node Shell Vars, Install, Built-in, Top
@appendix Variables Set or Used by the Shell
@c be clearer for each var, who sets it, who uses it
@cindex variables, set or used by the shell
@cindex shell variables, set or used by the shell
The following variables are set by the shell.
@xref{Variable Mechanics}, for information on shell variables.
@c terminology needing defs or refs:
@c parent, working directory, user ID, effective user ID, full
@c pathname, instance of BASH, search path, internal field separators,
@c shell script, password file, system spool directory, primary prompt
@c string, secondary prompt string, execution trace, decoded prompt
@c string, exapnsion, end-of-file characters, exit, pathname
@c expansion, history expansion, tokenization, symbolic links, logical
@c chain of directories, complete a hostname, directory stack
@c what is difference between IS and EXPANDS TO?
@c ? I think almost every 'expands to' here should be 'is'
@table @code
@item PPID
This is the @sc{pid} (process id) of the shell's parent.
@item PWD
This is the current working directory.
(It's called @code{PWD} because it is the directory name the @code{pwd}
command would report.)
It is updated when you change directories with the @code{cd} command.
@item OLDPWD
This is the previous working directory.
When you change directories with the @code{cd} command,
the directory you move to goes into @code{PWD} and the directory
you move from goes into @code{OLDPWD}.
@item REPLY
This is set by the @code{read} built-in command (@pxref{Built-in}) when
no arguments are supplied.
@item UID
This expands to the user @sc{id} of the current user.
@item EUID
This expands to the effective user @sc{id} of the current user.
@item BASH
This expands to the full pathname used to invoke this instance of BASH.
@item BASH_VERSION
This expands to the version number of this instance of BASH.
@item SHLVL
This is incremented by one each time an instance of BASH is started.
@c KELLEM: the following variables are from posix.2 and should be in bash
@c these include RANDOM, SECONDS, and LINENO [not in 1.06.25]
@item RANDOM
Each time this variable is referenced, a random integer is generated.
The sequence of random numbers may be initialized by assigning a value
to @code{RANDOM}. If @code{RANDOM} is unset, it will lose its special
properties, even if it is subsequently reset.@refill
@item SECONDS
Each time this variable is referenced, the number of seconds since shell
invocation is returned. If a value is assigned to @code{SECONDS}, the
value returned upon subsequent references is the number of seconds since
the assignment plus the value assigned. If @code{SECONDS} is unset, it
will lose its special properties, even if it is subsequently reset.
@item LINENO
Each time this variable is referenced, the shell substitutes a decimal
number representing the current sequential line number (starting with 1)
within a script or function. When not in a script or function, the
value substituted is not guaranteed to be meaningful. When in a
function, the value is not the number of the source line that the
command appears on (that information has been lost by the time the
function is executed), but is an approximation of the number of commands
executed in the current function. If @code{LINENO} is unset, it will
lose its special properties, even if it is subsequently reset.
@end table
The following variables are used by the shell. In some cases, as noted
below, BASH assigns these variables default values:
@table @code
@item HOME
This represents the default argument for the @code{cd} command. (That
is, the command @samp{cd} with no arguments will connect to this
directory.) It is usually your login directory. For example:
@example
HOME=/usr/home/close
@end example
@noindent
@code{HOME} is automatically set to your login directory when you log in.
@item PATH
This is the search path to use when the shell looks for program files
referenced in commands. Separate directory names using colons. Here's
an example:
@c explain
@example
/usr/gnu/bin:/usr/local/bin:.:/usr/ucb:/bin:/usr/bin/X11:/usr/bin
@end example
@item CDPATH
This is the search path for the @code{cd} command. Separate directory
names using colons. Here's an example:
@example
CDPATH=.:~:/usr/src
@end example
@item IFS
This defines the internal field separators. These are the characters
that separate words.
@c what words? where?
It has a default value of space, tab, and newline characters. Here's an
example:
@example
IFS=':'
@end example
@noindent
This allows you to read the password file as separate fields.
@item ENV
If this parameter is set when BASH is executing a shell script, its
value is interpreted as a file name containing commands to initialize
the shell (like @file{.bashrc} for interactive shells).
@item MAIL
This is the file name to use as your mailbox. If this file is non-zero
in length and has been modified since the last time the shell checked
the file, the shell displays the message ``@code{you have mail}''. You
control how often the shell checks this file by setting the @code{MAILCHECK}
variable.
Here's an example using the @code{MAIL} variable:
@example
MAIL=/usr/homes/close/mbox
@end example
@noindent
This causes the shell to check for mail in @file{/usr/homes/close/mbox}
rather than the system spool directory.
@item MAILCHECK
This specifies the amount of time that must pass before the shell will
check the file named by the @code{MAIL} variable to see if it has changed. The
default is 60 seconds (1 minute). An interval of 0 causes the shell
to look for mail before printing each prompt.
For example,
@example
MAILCHECK=600
@end example
@noindent
causes the shell to check for mail before printing a prompt if 600
seconds have passed since the last check.
@item MAILPATH
@c how relates to MAIL variable? what if both set?
This specifies multiple mailboxes for the shell to check. It is the
path the shell uses to check the named files for modifications (receipt
of mail). To distinguish which file has received mail, you can follow
each file name with a @samp{%} and some unique text which is printed
when mail is received. Separate file names with colons. Here's an
example:
@example
MAILPATH='/usr/homes/close/mbox?"You have mail":~/shell-mail?"$_ has
mail!"'
@end example
@noindent
This causes the shell to print ``You have mail'' whenever it detects a
change in the modification time of the file
@file{/usr/homes/close/mbox}. Additionally, the file
@file{/usr/homes/close/shell-mail} is also checked, and the message
``/usr/homes/close/shell-mail has mail!'' is printed whenever a change
is detected in its modification time.@refill
@c KELLEM added MAIL_WARNING
@item MAIL_WARNING
If this variable is set and one of the specified mail boxes has been
accessed since the last time BASH checked, then the message ``The mail
in <mailfile> has been read!'' is printed.@refill
@item PS1
This is the primary prompt string. By default it is @samp{bash\$ }.
Here's an example:
@example
PS1="$(whoami)@@$(hostname)$ "
@end example
@noindent
This sets the primary prompt string to be the login name of the current
user, followed by the name of the computer, followed by a dollar sign.
@item PS2
This is the secondary prompt string. By default it is @samp{bash>}.
For example,
@example
PS2='more> '
@end example
@noindent
sets the secondary prompt string to @samp{more> }. This is printed
whenever bash needs more input to complete a command.
@c elaborate on when needs more input?
@item PS4
This is the prompt string printed before each command BASH displays
during an execution trace. By default, it is @samp{+}.
@item NO_PROMPT_VARS
If this is set, the decoded prompt string does not undergo further
expansion.
@item HISTSIZE
This is the number of commands to remember in the command history list
(@pxref{History}). Its default value is 500.
@item HISTFILE
This is the name of the file in which the command history list is saved
(@pxref{History}).
@c apparently: saved over sessions; history of current session not
@c there yet if you look (e.g. with emacs or cat)
@item PROMPT_COMMAND
If this is set, the value is executed as a command prior to issuing
each primary prompt.
@c bfox: if a shell is running disconnected from tty, every read from
@c tty gives it eof -- this way it goes away after n tries
@item IGNOREEOF
@itemx ignoreeof
This controls the action of the shell on receipt of an end-of-file
character as the sole input. If set, the value is the number of
consecutive end-of-file characters typed before bash will exit.
If the variable exists but does not have a numeric value, or has no
value, the default value is 10. If it does not exist, an end-of-file
signifies the end of input to the shell. This is only in effect for
interactive shells.
@item HOSTTYPE
This is automatically set to a string that uniquely describes the type
of machine on which BASH is executing. The default is
system-dependent.
@c example...
@c KELLEM, adding TMOUT: TMOUT is from posix.2a, I believe
@item TMOUT
If this is set to a value greater than zero, the value is interpreted as
the number of seconds to wait for input after issuing the primary
prompt. BASH will terminate after waiting for the number of seconds.
@item notify
If this is set, BASH will report terminated background jobs
immediately, rather than waiting until printing the next primary prompt
(@pxref{notify}).
@item history_control
@c tested 12/26, ok
If this is set to a value of @code{ignorespace}, lines that begin with a
space won't be entered in the history list.
If this is set to a value of @code{ignoredups}, lines that match the last
line entered in the history list won't be recorded.
If this is unset, or set to any other value than those above, all
lines read by the shell are saved in the history list.
@item glob_dot_filenames
If this is set, BASH includes file names beginning with a @samp{.} in
the results of pathname expansion.
@item allow_null_glob_expansion
Normally, a filename pattern that doesn't match any files is left in the
command as is (expands to itself) . For example, @samp{*.foo} is left
as is if there are no files ending in @samp{.foo}.
If @code{allow_null_glob_expansion} is set, however, a pattern that doesn't
match anything is removed from the command (expands to a null file name).
@c example?
@c must doc in appropriate parts of manual
@item histchars
This represents the two characters which control history expansion and
tokenization. The first character is the history expansion character;
that is, the character which signals the start of a history expansion
(normally @samp{!}).
The second character is the character which signifies that the
remainder of the line is a comment, when found as the first character
of a word.
@c ? default histchars was empty in 1.06, 2/13/91
@c I tried setting it, and ! stopped being special but the new chars
@c didn't seem to do anything.
@item nolinks
If this is set, the shell doesn't follow symbolic links when doing
commands that change the current working directory. By default, BASH
follows the logical chain of directories when performing commands such
as @code{cd}.
@item hostname_completion_file
This contains the name of a file, in the same format as
@file{/etc/hosts}, that should be read when the shell needs to
complete a hostname. You can change the file name interactively; the
next time you want to complete a hostname BASH adds the contents of the
new file to the already existing database.@refill
@c really telling user to modify a public file?!?
@item noclobber
If this is set, BASH will not overwrite an existing file with the
@samp{>}, @samp{>&}, and @samp{<>} redirection operators.
@c KELLEM: <> opens a file descriptor for reading and writing. from posix
Such an attempt to overwrite a file will generate an error message.
You can override this via the @samp{>|} redirection operator. The @samp{>>}
(append) redirection operator will still work on existing files because
it only appends to the file and doesn't erase the file's current contents.
@item auto_resume
This variable determines whether a command may restart a suspended job
rather than starting a new one.
@xref{Resuming}, for more information.
@item no_exit_on_failed_exec
If this variable exists, the shell doesn't exit if it can't execute the
file specified in an @code{exec} command (@pxref{Built-in}).
@item cdable_vars
If this is set, an argument to the @code{cd} built-in command that is
not a directory is assumed to be the name of a variable whose value
represents the directory to which you would like to @code{cd}.
@item pushd_silent
If this is set, the @code{pushd} and @code{popd} built-in commands will
not print the current directory stack after successful execution.
@end table
@node Install, Invoke, Shell Vars, Top
@appendix Installing BASH
This appendix tells how to install BASH on a machine.
If BASH is already on your machine, or you are not the person installing
it, ignore this appendix.
@cindex installing BASH
@cindex BASH, installation
To install BASH you simply type @kbd{make}. @c really?
The BASH @file{Makefile} @c really a file name?
tries to dynamically figure out what kind of machine and operating
system you are using. It makes an educated guess based on the
information it finds.
During the @code{make} process, a message is displayed describing what
machine and operating system has been chosen for you. This information
is also saved in the file @file{.machine} so you can look at it later.
Therefore, for most machines, simply follow this simple checklist to
install BASH:
@enumerate
@item
Type @kbd{make}.
@item
Wait for the compilation to finish.
@item
Type @kbd{./bash} to see if the compile worked.
@c how can you tell if it worked?
@item
Type @kbd{cp ./bash /usr/gnu/bin/bash} (or wherever you keep GNU
binaries) to copy BASH to your binaries directory.
@end enumerate
@menu
* Problems:: What to do if BASH doesn't install quite so easily.
* Files:: Files used in the @code{make} process.
* Porting:: Porting BASH to a new machine.
* Bugs:: What to do if you Discover Bugs in BASH.
@end menu
@node Problems, Files, Install, Install
@appendixsec What if it Doesn't Install so Easily?
@cindex installation, problems with
@cindex BASH, installation problems
Sometimes BASH gets confused and will make the wrong assumptions about
your machine or operating system. If the displayed information (also
found in @file{.machine}) is incorrect, you will have to edit the file
@file{machines.h} and provide the appropriate information so that BASH
can be installed correctly. The complete instructions for doing this
are located in the @file{machines.h} file.
@c what font should UNKNOWN_MACHINE be?
However, if BASH says that your machine type is an @sc{UNKNOWN_MACHINE},
or BASH thought it knew something about your machine but was wrong,
then reading the next few sections could be of use to you
@xref{Files}, and @ref{Porting}, for more information).
@node Files, Porting, Problems, Install
@appendixsec Files Used in the @code{make} Process.
@cindex installation, files used in
@cindex BASH, files used in installation of
The following files are used during the installation of BASH, in the
@code{make} process:
@table @code
@item Makefile
This is responsible for making the actual @file{Makefile} that is used
to create Bash. It runs the C preprocessor (usually located in
@file{/lib/cpp}) on the file @file{cpp-Makefile}, producing the output
file @file{bash-Makefile}.
@item cpp-Makefile
This is a file of C comments and text. It contains
@code{ifdefs} that control what files get compiled and which flags
are passed to the various C files comprising BASH. It includes a file
called @file{machines.h}.
@item machines.h
This file contains the basic compilation parameters for all of the
machines to which BASH has been ported. This file consists of a series
of conditional blocks, one per machine type.
These conditional blocks are depend upon the unique identifier that
@file{cpp} has predefined for this machine. In some cases, additional
information can be passed from @file{Makefile}. It is possible to pass
information such as whether or not a particular file is available on
this system, and so on.
@item bash-Makefile
This is the output from the initial stage of @code{make}. It is a
stripped down version of @file{cpp-Makefile} which is tailor-made for
your machine and operating system. All subsequent @code{makes} use
this file.
@end table
@node Porting, Bugs, Files, Install
@appendixsec What if You Have to Port to a New Machine?
@cindex installation, porting to a new machine
@cindex BASH, porting to a new machine
@cindex porting BASH to a new machine
To port BASH to a previously unsupported
machine, you need to create a block in @file{machines.h}
that is conditional based on a unique identifier present in your
version of the C preprocessor.
If you don't know what that symbol is, you might try the following
simple test:
@example
bash$ echo "main () @{ @}" > foo.c
bash$ cc -v foo.c
@end example
@noindent
The first command puts a small C program into the file @file{foo.c},
and the second program compiles that program.
The @code{-v} option ???. @c what does it do?
@noindent
Look for something of the form @code{-D}@var{machine} in the output of
@code{cc}, where @var{machine} is an identifier for your machine. If
your machine's C preprocessor doesn't have a unique identifier, you will
have to define the identifier in @file{Makefile} manually.
Let's say you have a machine from Yoyodyne Industries, called the YoYo.
It runs a version of @sc{bsd}, so it is reasonably compatible.
@c compatible with what?
However, the
@file{cpp} file on this YoYo machine doesn't define any unique identifiers.
You should change the @file{Makefile} line for @code{CPPFLAGS} to:
@example
CPPFLAGS = -P -DYoYo
@end example
@noindent
Then, in @file{machines.h}, make a copy of the block for
@code{UNKNOWN_MACHINE}, and change the conditional to:@refill
@example
#if defined (YoYo)
@end example
@noindent
Inside the YoYo block, define @samp{M_MACHINE="YoYo"} and
@samp{M_OS=BSD}. You also modify the existing defines to match your
machine's software.
If BASH still won't compile, perhaps because of missing code that is
required for your YoYo machine, you will have to write that code and
place it within a conditional block based on YoYo.
Most machines aren't that difficult; simply redefining a few of the
default values is sufficient. If you do run across a difficult machine,
please send all fixes and changes to bash-maintainers@@ai.mit.edu in the
form of context diffs:
@example
diff -c orig-machines.h machines.h >machines.diffs
@end example
@noindent
Please include information about which version of the shell you have.
@node Bugs, , Porting, Install
@appendixsec Reporting Bugs
@cindex BASH, reporting bugs
If you find a bug in BASH, you should report it. But first you should
make sure that it really is a bug and that it appears in the latest
version of BASH that is available.
@c how can you find out if it is the latest BASH?
Once you have ascertained that a bug really exists, you are welcome to
mail in a bug report. If you have a fix, please mail that too!
Suggestions and ``philosophical'' bug reports should be mailed to
bug-bash@@ai.mit.edu. Genuine bug reports should be mailed to the same
place, or to bash-maintainers@@ai.mit.edu.
@emph{All} bug reports should include:
@itemize @bullet
@item
The version number of BASH.
@c how find it out?
@item
The hardware and operating system used.
@item
The compiler used to compile BASH.
@item
A description of the bug's behavior.
@item
A short script or ``recipe'' which demonstrates the bug.
@end itemize
Without this information, it is generally not possible to successfully
debug BASH. Usually, without this information, the bug won't manifest
itself!
Discussion and questions about BASH in general (including questions
about this documentation) can be sent to bug-maintainers@@ai.mit.edu.
@node Invoke, Start-up, Install, Top
@appendix Invoking BASH
@c bad title -- more is covered
@cindex invoking BASH
@cindex BASH, invoking
@c intro material might be useful elsewhere
The operating system starts a shell for you when you log in.
This shell operates interactively; that is, it prompts you for commands
and processes those commands. Logging off the system ends this login
shell.
@cindex shell, interactive
@cindex shell, login
@cindex shell, non-interactive
A login shell is one that's been started with the @samp{-login} flag,
or one whose first character of argument 0 is a @samp{-}.
@c I don't understand the last sntence
An
interactive shell is one that has been started with the
@samp{-i} flag, or one whose standard input and standard output are
both connected to terminals.
A shell doesn't always have to be interactive. For example, if you use
a sequence of commands frequently, you can save time typing by storing
those commands in a file
@c ? is that the def of a shell script?
and direct the shell to execute this command
file when you need it. When this command file is executed a new
non-interactive shell
is started to read and execute the commands in that file.
@c not necessarily new shell
You can tell if a shell is interactive or not by examining the contents
of the variable @code{PS1}. It is unset in non-interactive shells, and set in
interactive ones.
@c Why/when do you want to tell? If you're typing at the shell, you
@c already know it is interactive. If you're writing a file to be
@c executed by a noninteractive shell, that file knows it's noninteractive.
@menu
* Invoke Order:: What files are invokes upon login, logout
and starting non-interactive and non-login
shells.
* Invoke Options:: Options that modify the shell invocation
process.
* Signals:: How BASH handles signals as an interactive
shell.
* Tilde:: How BASH handles tilde expansion.
* Splitting:: How BASH handles word splitting and pathname
expansion.
@end menu
@node Invoke Order, Invoke Options, Invoke, Invoke
@appendixsec Automatic Script Execution
@cindex invoking BASH, file order when
@cindex shell, login file order
@cindex shell, logout file order
Upon starting a login shell, the system
@c ? the system? or bash?
looks for a file containing
system-wide start-up instructions for BASH and reads and executes it.
Usually these instructions are in a file called @file{/etc/profile}.
Next the system looks for start-up instructions for your account and
reads and executes it. These instructions are found in one of the
following files; the system searches for the following files, in order,
and reads and executes the first one it finds:
@table @file
@item ~/.bash_profile
@item ~/.bash_login
@item ~/.profile
@end table
@noindent
Since the chosen file contains start-up instructions for @emph{your}
account, you can modify and ``personalize'' this file if you want.
@xref{Start-up}, for an example of this type of file
(@file{~/.bash_profile}). If BASH can't find any of these files,
BASH starts with a default environment; no error message is given.
When exiting a login shell, BASH reads and executes the file
@file{~/.bash_logout}, if it exists.
@c bash IS the login shell that is exiting
@xref{Start-up}, for an example of this type of file.
@cindex shell, interactive file order
@c what causes non-login interacive shell to start up?
Upon starting a non-login, interactive shell, BASH
@c bash IS that shell
reads and executes the
file @file{~/.bashrc} if it exists.
@c ? mnemonic for 'rc'
@xref{Start-up}, for an example of this type of file.
@cindex shell, non-interactive file order
@c what causes non-interacive shell to start up?
Upon starting a non-interactive shell, BASH
@c bash IS that shell
checks to see if the
environment variable
@c ? env var = shell var ?
@code{ENV} is non-null, and reads and executes the
file named by that variable.
@node Invoke Options, Signals, Invoke Order, Invoke
@appendixsec Options That Modify the Shell Invocation Process
To invoke BASH you can type:
@c why? you have one already
@c text below says options come before -...
@example
bash @r{[}-acefhiknstuvx@r{]} @r{[}@var{options}@r{]}
@end example
@noindent
where @var{options} represents one of the multi-character options
described a bit later in this section. BASH interprets the following
single-character options when it is invoked:
@cindex invoking BASH, options
@cindex shell, invocation options
@c compare to 'set' options. maybe combine doc
@c listed here as
@table @code
@item a
Automatically mark variables which are modified or created for export.
@c how does string combine with other single-char options?
@item c @var{string}
Commands are read from @var{string}.
@item e
Exit immediately if a command exits with a nonzero status.
@item f
Disable pathname generation.
@item h
Locate and remember function commands as functions are defined.
@item i
This makes the shell interactive.
@item k
Place all keyword arguments for a command in the environment for that
command (not just those arguments that precede the command name).
@item n
Read commands but don't execute them.
@item s
If this option is present, or if no arguments remain after option
processing, commands are read from the standard input. (This option
allows the positional parameters to be set when invoking an interactive
shell.)
@item t
Exit after reading and executing one command.
@item u
Treat unset variables as an error when performing parameter expansion.
@item v
Print shell input lines as they are read.
@item x
After expanding each command, display the value of @code{PS4} followed
by the command and its expanded arguments.
@end table
BASH also interprets a number of multi-character options. These
options must appear on the command line @emph{before} the single-character
options in order to be recognized. These options are:@refill
@table @code
@item -norc
Do not load the personal initialization file @file{~/.bashrc}. This is
the default if the shell name is @code{sh}.
@c ???
@item -noprofile
Do not read either @file{/etc/profile} or @file{~/.bash_profile}, if
this is a login shell.
@c what about the other profiles? ~/.bash_login, ~/.profile
@item -rcfile @var{file}
Execute commands from @var{file} instead of from the standard personal
initialization file @file{~/.bashrc}.
@item -version
Show the version number of this instance of BASH when starting.
@c this instance = the bash starting up?
@item -quiet
Do not be verbose when starting up (do not show the shell version or
any other information).
@item -login
Make BASH act as if it had been invoked by @code{login}.
@item -nobraceexpansion
Do not perform curly brace expansion (@pxref{Grouping}).
@item -nolineediting
Do not use the readline library to read command lines if this shell is
interactive.
@end table
If arguments remain after option processing,
@c no args shown in syntax above
and neither the
@samp{-c} nor the @samp{-s} option has been supplied,
@c s not explained well -- didn't show use of an arg
then the first
argument is assumed to be the name of a file containing shell commands.
If BASH is invoked in this fashion, the variable @code{0} is set to the name of the
file, and the positional parameters are set to the remaining arguments.
BASH reads and executes commands from this file, then exits.
@node Signals, Prompt, Invoke Options, Invoke
@appendixsec How BASH Handles Signals
@cindex BASH, signal handling in
@cindex signals, how BASH handles
@cindex signal handling
@c how relates to signals in process chapter?
@c below:explain job control, synchronous job, inherited, command
@c substitution, kernel, process group id
When BASH is interactive, it ignores @code{SIGTERM}. This means that
@samp{kill 0} will not kill an interactive shell. Also, @code{SIGINT}
is caught and ignored, so that @code{wait} is interruptible.
In all cases, BASH ignores @code{SIGQUIT}.
If job control is in effect, bash ignores @code{SIGTTIN},
@code{SIGTTOU}, and @code{SIGTSTP}. Synchronous jobs started by BASH
have signals set to the values inherited by the shell from its parent.
Background jobs (jobs started with @samp{&}) ignore @code{SIGINT} and
@code{SIGQUIT}.
Commands run as a result of command substitution ignore the
keyboard-generated job control signals @code{SIGTTIN}, @code{SIGTTOU},
and @code{SIGTSTP}.
Here's a description of the signals listed above:
@table @code
@item SIGINT
This is the signal generated (normally) by @kbd{C-c} on the keyboard.
This signal will kill most processes, although a program may choose to
ignore @code{SIGINT}. @code{SIGINT} also allows a process to clean up after itself
before dying.
@item SIGQUIT
This is the signal generated (normally) by @kbd{C-\} on the keyboard.
@code{SIGQUIT} is identical to @code{SIGINT} except that it requests that the
operating system produce a diagnostics file (called a @dfn{core dump}
which is placed into a file named @file{core}).
@item SIGTERM
@code{SIGTERM} is similar to @code{SIGINT} except that it is normally produced by a
software program and not from the @kbd{C-c} on the keyboard. Note that
some programs treat @code{SIGTERM} differently from @code{SIGINT}.
@item SIGTSTP
@code{SIGTSTP} is the signal sent (normally) by the @kbd{C-z} key on the
keyboard. Some programs may ignore this signal. This signal does not
kill the process but instead @emph{stops} the process, putting the
program into a suspended state.
@item SIGTTIN
The kernel sends the signal @code{SIGTTIN} to a job/process group that is not
in the foreground (that is, the process group's process group @sc{id} is not
equal to the terminal's foreground process group @sc{id}) and attempts to
read from the terminal.
@item SIGTTOU
The kernel sends the signal @code{SIGTTOU} to a job/process group that is not
in the foreground and attempts to write to the terminal if, and only
if, the terminal has the @sc{tostop} bit set in its local flags word (you
can set this bit with @samp{stty tostop}).
@c tostop: code or sc?
@c what's tostop? local flags word?
@end table
@c what is this topic really? sections removed from another appendix
@node Command Processing
@appendix Command Processing
@node Splitting, , Tilde, Invoke
@appendixsec Word Splitting and Pathname Expansion
@c purpose of section -- what is effect of splitting? why do we care?
@cindex word splitting
@cindex splitting, words
@c ???
The shell scans the results of parameter expansion and command
substitution that did not occur within double quotes for word
splitting.
The shell treats each character of the variable @code{IFS} as a delimiter, and
splits the results of the other expansions
@c other than what?
into words on these
characters. The default value of @code{IFS} is exactly
@samp{<space><TAB><newline>}.
@c SPCTAB ... how notate?
@xref{Shell Vars}, for more information
on how to change the value of @code{IFS}.
If @code{IFS} is unset or null, no splitting is done. Otherwise, each occurrence
of an @code{IFS} character is treated as a delimiter.
Explicit null arguments (@samp{""} or @samp{''} -- i.e., single or
double quotes with nothing between them) are retained.
Implicit null arguments, resulting from the expansion of parameters
that have no values,
@c no value -- unset? null value?
are removed. If no expansion occurs, then no splitting is performed.
@cindex expansion, pathname
@cindex pathname expansion
After word splitting, BASH scans each word for the special characters
@samp{*}, @samp{?}, and @samp{[@dots{}]}, unless the @samp{-f} option is
present. If one of these characters appears, then the word is regarded
as a pattern, and replaced with an alphabetically sorted list of
pathnames matching the pattern. @xref{File Names}, for more
information on these special characters.
If no matching pathnames are found, and the shell variable
@code{allow_null_glob_expansion} is unset, the word is left unchanged
(@pxref{Shell Vars}). If the variable is set, the word is removed if
no matches are found.
@c paragraph unclear
When a pattern is used for pathname generation, the character @samp{.}
(at the start of a name or immediately following a slash) must be
matched explicitly, unless the shell variable @code{glob_dot_filenames}
is set (@pxref{Shell Vars}). The slash character must always be
matched explicitly. In other cases, the @samp{.} character is not
treated specially.
@node Start-up, Advanced Scripts, Invoke, Top
@appendix Sample Script Files
@c some redundancy between invocation appendix and this one re login files
When you first log in, a shell process is started that establishes the
environment for your session (@pxref{Invoke Order}). A system-wide
login script assigns default values to environment variables creating a
basic, default environment (@pxref{Environment}).
(A login script is simply a file that contains commands that customize
the environment.)
@cindex start-up files, sample
@cindex login file samples
This default environment can be quite restrictive. BASH uses various
local login scripts to allow you to change and ``personalize'' the
default environment (@pxref{Invoke Order}). If a local login scripts
exists, it is executed by the shell before you get a shell prompt,
customizing your environment for you.
@menu
* Login Script:: Sample of a login script.
* Logout Script:: Sample of a logout script.
* Other Scripts:: Sample of a non-login, interactive shell
script.
@end menu
@node Login Script, Logout Script, Start-up, Start-up
@appendixsec Login Scripts
@c some redundancy between invocation appendix and this one re login files
@cindex login script
A local login script allows you to change the default environment to
fit your needs. If you have one it resides in your home directory.
Note that names for this script begin with a dot (@samp{.}), so the
file remains hidden when performing a standard directory listing
(@code{ls}). You have to type @code{ls -a} to see if you have any
local login scripts. If you do, it will be called one of the following
names:
@c if you don't have one, can create one -- how know what put in it?
@c Be clear it's done after system file, so needn't duplicate what's there
@table @file
@item ~/.bash_profile
@item ~/.bash_login
@item ~/.profile
@end table
Since this file contains start-up instructions for @emph{your} account,
you can modify this file to create an environment
specific to your needs. Here is an example of a BASH start-up file for
login shells, @file{~/.bash_profile}:
@c need to explain sample scripts
@cindex login script, sample of
@cindex script, sample of a login
@example
# File: /usr/gnu/lib/Bash_profile
# Startup file for bash login shells.
#
default_dir=/usr/gnu/lib/
@c how can your login shell be noninteractive?
# Test to see if this is an interactive shell.
if [ "$PS1" ]; then
PS1='\u@@\h(\#)\$ '@c KELLEM added \ before $
ignoreeof=3
fi
LOGIN_SHELL=true
# If the user has her own init file, then use that one, else use
# the canonical one.
@c why in separate rc file instead of right here?
if [ -f ~/.bashrc ]; then
source ~/.bashrc
else if [ -f $@{default_dir@}Bashrc ]; then
source $@{default_dir@}Bashrc;
fi
fi
@end example
@node Logout Script, Other Scripts, Login Script, Start-up
@appendixsec Logout Scripts
A logout script allows you to automate a variety of tasks like starting
background processes with a @code{nohup} option, running file clean-up
routines, or simply displaying a logout message when you log out. If a
@file{.bash_logout} file exits in your home directory, it is executed
automatically when you log out.
@c nohup not illustrated in sample script
The logout script can contain any commands that you might type at the
shell prompt. However, a logout script is most useful when used to
display information about the session just ending and to run background
commands after you log out.
Here's an example of a simple BASH logout file, @file{~/.bash_logout}:
@cindex logout script
@cindex logout script, sample of
@cindex script, sample of a logout
@example
# File: /usr/close/.bash_logout
# BASH log off file
# First clear the screen.
clear
# Clean up my files.
echo "cleaning things up now"
rm *.o
# Print a logout message.
echo `whoami` "logged out on" `date`
# Then say goodbye.
echo "Au revoir"
@end example
@node Other Scripts, Inputrc File, Logout Script, Start-up
@appendixsec Non-login, Interactive Scripts
@c what about noninteracive scripts?
All login scripts are run when you first log in.
@c all ??
In addition, login
scripts that end in @samp{rc} are executed each time your current shell
creates a subshell.
@c ? what are the possible rc script names?
@c ?when does it run a subshell?
Here's an example of a BASH start-up file for
non-login, interactive shells, @file{~/.bashrc}:
@cindex interactive non-login script
@cindex interactive non-login script, sample of
@cindex script, sample of an interactive non-login
@example
# File: /usr/gnu/lib/Bashrc
# Bourne Again SHell init file.
#
# Files you make look like rw-rw-r
umask 002
# Don't make useless coredump files. If you want a coredump,
# say "ulimit -c unlimited" and then cause a segmentation fault.
ulimit -c 0
# Sometimes, there are lots of places that one can find tex
# inputs.
export TEXINPUTS=.:$HOME/bin:/usr/lib/tex/inputs:/usr/local/lib/tex/inputs
# Where's the Gnu stuff at?
GNU=/usr/gnu/bin
X11=/usr/bin/X11
UTIL_PATH=$GNU:$X11
STANDARD_PATH=/usr/local/bin:/usr/ucb:/bin:/usr/bin:/usr/etc:/etc:/usr/games
if [ "$HOSTTYPE" = "sony" ]; then STANDARD_PATH=$STANDARD_PATH:/usr/sony/bin; fi
if [ -d $HOME/bin/$HOSTTYPE ]; then
MY_PATH=$HOME/bin/$HOSTTYPE
fi
if [ -d $HOME/bin ]; then
MY_PATH=$MY_PATH:$HOME/bin
fi
PATH=.:$MY_PATH:$UTIL_PATH:$STANDARD_PATH
@c section claims to be about interactive script -- why need to test?
# If running interactively, then:
if [ "$PS1" ]; then
# Here are a couple of functions to make csh user's lives easier.
setenv () @{
export $1="$2"
@}
unsetenv () @{
unset $*
@}
# Here are a couple of functions that make *my* life easier.
showme () @{
local files=$(type -all -path $1)
if [ "$files" ]; then ls -l $files; else echo "No such file."; fi
@}
# Set ignoreeof if you don't want EOF as the sole input to the shell to
# immediately signal a quit condition. This only happens at the start
# of a line if the line is empty, and you haven't just deleted a character
# with C-d. I turn this on in ~/.bash_profile so that only login shells
# have the right to be obnoxious.
# ignoreeof=
# Set auto_resume if you want TWENEX style behavior for command names.
auto_resume=
# Set notify if you want to be asynchronously notified about background
# job completion.
notify=
# Make it so that failed `exec' commands don't flush this shell.
no_exit_on_failed_exec=
@c section claims to be about non-login script
if [ ! "$LOGIN_SHELL" ]; then
PS1="\u@@\h\$ "
fi
HISTSIZE=256
MAILCHECK=60
# A couple of default aliases.
alias j='jobs -l'
alias po=popd
alias pu=pushd
alias ls='ls -F'
HOST=$(hostname | sed -e 's/\.*//')
xtitle () @{ echo -n -e "\033]l$*\033" @}
if [ -f ~/.bash_aliases ]; then
source ~/.bash_aliases
fi
fi
@end example
@node Advanced Scripts, Tools, Start-up, Top
@appendix Writing and Debugging Scripts
@cindex debugging shell scripts
@cindex scripts, debugging
@cindex shell scripts, debugging
When writing scripts, it's always possible that mistypings and other
errors can occur. In complicated scripts
errors may be difficult to track down and fix.
The shell can make things simpler though, with its debugging options,
like @samp{-v} and @samp{-x}. All can be invoked by command arguments
to BASH or through the @code{set} command (@pxref{Built-in}). For
example, @code{bash -v} or @code{set -v}.
@c substitute new 'set -o ...' version of above
The @samp{-v} option sets the shell to verbose mode. This causes
command lines to be displayed as they are read.
@c read in general? or just from a script (file)?
This is useful for
finding syntax errors. You can use this option in conjunction with
the @samp{-n} option,
@c substitute new 'set -o ...' version of above
which prevents the execution of commands.
However, note that saying @code{set -n} makes a terminal useless until
an end-of-file is typed.
@c ? how do you type eof?
The @samp{-x} option displays each command as it is executed, following
all substitutions.
@c substitutions such as ...
This lets you see what is going on as the shell
program runs.
@c ? program = script?
It shows you what the shell did to your command line as
a result of all the substitutions that took place. This is useful to
see if your command lines do what you wanted them to do.
In long shell scripts you can get lots of unwanted and unnecessary
debugging information from the shell when the
@samp{-x} option is used. You can reduce the amount of output by
turning this option on (@code{set -x})
@c substitute new 'set -o ...' version of above
where you need it and turning it off (@code{set +x}) when you don't.@refill
@c you mean put 'set ' in the script itslf?
Adding @code{echo} statements to the shell script also helps when
debugging. It's like having @code{print} statments in a program.
You can even check for unset shell variables with the @samp{-u} option.
When you use this option, attempts to substitute variables that have not
been set causes an error message and execution is stopped.
@c KELLEM: the next sentence sounds incorrect, will have to verify
@c All options can be turned off by saying @code{set -}.
The current setting of the shell options is available as @samp{$-}.
@menu
* More Scripts:: Advanced sample scripts.
@end menu
@node More Scripts, , Advanced Scripts, Advanced Scripts
@appendixsec More Examples of Shell Scripts
@cindex shell scripts, advanced examples of
@cindex scripts, advanced examples of
Here's an example of a more advanced shell script.
@c more advanced than what?
This script tells you which file will be executed when you
use the command you give it as an argument. It uses @code{sed} to
split your path, inserting dots in place of null strings to preserve
the shell semantics. It tests each directory on your path for an
executable file whose name is the same as the argument you gave to the
script. If it finds one, it tells you what it is and exits with a
successful status. If no executable files are found, the script exits
with a failure status.
@example
#
# which -- find out which command in $PATH is executed
#
# adapted from Kernighan and Pike
#
opath=$PATH
PATH=/usr/ucb:/bin:/usr/bin
case $# in
0)
echo "usage: $0 command" 1>&2
exit 1
;;
*)
;;
esac
@c !!! my god!!!! teco**(teco**2)
for i in $(echo $opath | sed 's/^:/.:/
s/::/:.:/g
s/$:/:./
s/:/ /g')
do
if [ -x $i/$1 ] ; then
echo $i/$1
exit 0
fi
done
exit 1
@end example
Here's another example, submitted by Bennett Todd
(bet@@orion.mc.duke.edu). It forces the commands run as the arguments
to the script to die after some timeout. This is handy for debugging
full-screen programs (like Emacs) that, if they get hung, wedge the
terminal fatally.
@example
#!/bin/sh
# Launch a sleeping killer-offer
progname=`basename $0`
timeout=10
signal=TERM
while test $# -gt 2 -a `expr "x$1" : "x-."` -gt 0
do
case "x$1"
in
x-t) shift; timeout=$1; shift;;
x-s) shift; signal=$1; shift;;
esac
done
if test $# -lt 1
then
echo "syntax: $0 [-t timeout] [-s signal] command" 1>&2
exit 1
fi
(sleep $timeout; kill -$signal $$) &
exec "$@@"
@end example
Finally, here's one more example of a shell script, submitted by Bill
Trost (trost@@reed.bitnet). It creates an extended version of the
shell's @code{pushd} & @code{popd} commands. It's slower than the
built-ins, but also adds a couple of features to @code{pushd}: negative
numeric arguments (given a dirstack of size 3, @code{pushd +2} is
equivalent to @code{pushd -1}), and named references. With a named
reference, a command of the form @code{pushd +xterm} will rotate the
directory stack to the first directory whose final component is
@file{xterm}. It uses the @samp{#} variable construct, and lots of
@code{sets} and @code{shifts}.
@example
# A shell-level version of pushd and popd. A bit slower, a bit
# cleverer. I added a feature, which is best described by
# example.
# Suppose you have the directory stack consisting of /tmp,
# /local/src/X11r4/mit/clients/xterm, and ~/prj/term (/tmp at the
# top). If you type "pushd +xterm", you'll end up in the first
# directory whose name end with "xterm".
# This is a complete rewrite of a similar function posted to
# gnu.bash.bug by Martin Tomes <mt00@@eurotherm.co.uk>. I've done
# a little benchmarking, and this version's pushd appears to be
# gobs faster; this is probably due to my use of the case
# construct instead of if/elif/fi. The if construct (at least in
# Bourne shell) has historically been very slow. Then again,
# popd was just as fast...?
# The alternative explanation is that his frequent use of the
# "cut" and "expr" commands slowed things down.
# This program expects the "seq" command to give a sequence of
# numbers from $1 to $2. I have a "seq" function which is
# usually very fast.
dirs () @{ echo $PWD $DIRS @}
pushd () @{
case "$1" in
"")
# Swap first two.
local here=$PWD
set $DIRS
cd "$1"
shift
DIRS="$here $*"
;;
+[0-9]*)
local save i=$@{1#+@}
set $PWD $DIRS
for i in `seq 1 $i`; do
[ "$1" = "" ] && @{ set $PWD $DIRS ; save= @}
save="$save $1"
shift
done
[ "$1" = "" ] || @{
cd $1
shift
DIRS="$* $save"
@}
;;
[-][0-9]*)
local dest=$@{1#-@}
set $PWD $DIRS
pushd +`expr $# - \\( $dest % $# \\)`
;;
+?*)
# Feature: pushd +foo will push to directory whose
# basename is "foo".
local wrap i goal=$@{1#+@} found=false
set $PWD $DIRS
for i; do
[ $@{i##*/@} = "$goal" ] && @{
cd $i
shift
DIRS="$* $wrap"
found=true
break
@}
wrap="$wrap $i"
shift
done
$found || @{
echo $@{goal@}: Directory not on stack. 1>&2
return 1
@}
;;
*)
[ ! -d $1 ] && @{
echo "$1": No such file or directory 1>&2
return 1
@}
DIRS="$PWD $DIRS"
cd $1
;;
esac
true $@{pushd_silent:-`dirs`@}
@}
popd () @{
[ -z "$DIRS" ] && @{
echo popd: Directory stack empty 1>&2
return 1
@}
case "$1" in
"")
set $DIRS
cd $1
shift
DIRS="$*"
;;
+*)
count=$1
set $DIRS
# Hack until builtin test works correctly with unary +
/bin/[ $count -gt $# ] && @{
echo popd: Directory stack not that deep 1>&2
return 1
@}
DIRS="`echo $DIRS | awk '@{ $'$count' = \"\"; print @}'`"
;;
*)
echo 'popd: usage: popd [ +n ]' 1>&2
return 1
;;
esac
true $@{pushd_silent:-`dirs`@}
@}
@end example
@node Tools, Authors, Advanced Scripts, Top
@appendix Useful Operating System Programs
This is the section that will include useful and related operating
system commands (NOT built-ins) to use with the shell and shell
procedures.
If you think that various utilities and commands used to support shell
programming belong in the shell programming manual, then go ahead and
add them yourself. Personally, I feel that there is no good determiner
of whether a utility belongs in the shell programming manual or whether
it belongs in the GNU operating system manual.
@c following note by JEMS
@c maybe should include those used in examples
@c (e.g. ls, rm cat, who, sort, date, more, wc, ...)
@node Authors, Concept Index, Tools, Top
@appendix Who and Where to Write
@c main topic is acknowledgments, not who to write
@cindex authors
This manual is a combined effort of a number of people. Diane Barlow
Close (close@@lunch.wpd.sgi.com) wrote the original draft. Julie
Sussman (jems@@altdorf.lcs.mit.edu) did the majority of reorganization
and the second draft. Without her help, this manual would probably
still be waiting to be written. Brian Fox (bfox@@ai.mit.edu) produced
the third draft, and provided technical advice for Diane and Julie.
Chet Ramey (chet@@cwns1.ins.cwru.edu) provided many examples for this
manual and wrote the BASH man page.
Richard Stallman (rms@@ai.mit.edu) provided editing and polishing of
the finished product.
Others who provided assistance of varying degrees are mentioned in the
acknowledgement section (@pxref{Thanks}).
Errors concerning this documentation should be sent to
bug-bash-manual@@ai.mit.edu. @xref{Bugs}, for information on where to
send bug reports for BASH itself.@refill
@node Concept Index, , Authors, Top
@unnumbered Concept Index
@printindex cp
@summarycontents
@contents
@bye