0% found this document useful (0 votes)
36 views

Bash Reference

Aprender bash útil para administración de procesos por consola

Uploaded by

EdgarP.Nash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Bash Reference

Aprender bash útil para administración de procesos por consola

Uploaded by

EdgarP.Nash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

BASH REFERENCE DEFINITIONS

This card describes version 2.02.0 of bash.


CONTENTS Several typefaces are used to clarify the meaning:
Aliasing ............................................................... 6 • Serifa Bold is used for computer input.
Arithmetic Evaluation........................................ 8 • Serifa Italic is used to indicate user input and for
Arrays .................................................................. 13 syntactic placeholders, such as variable or cmd.
Brace Expansion................................................. 6 • Serifa Roman is used for explanatory text.
Built-In Commands ............................................ 16
Command Line Arguments ............................... 3 blank − separator between words. Blanks consist of one
Command Substitution ...................................... 8 or more spaces and/or tab characters. In addition,
Conditional Expressions .................................... 15 words are terminated by any of the following
Control Commands ............................................ 14 characters:
Definitions ........................................................... 2 ; & ( ) | < > space tab newline
Execution Order ................................................. 13 command − a series of words.
Field Splitting ..................................................... 8
list − one or more pipelines. Can be separated by ;, &,
Functions ............................................................ 12
&&, || and optionally be terminated by ;, &.
History Substitution ........................................... 5
Input/Output ...................................................... 13 n − an integer.
Invocation and Startup ...................................... 3 name − a variable, alias, function or command name.
Job Ids and Job Control ..................................... 24
Options To set .................................................... 22 keyword − a reserved word in the bash language.
Options To shopt ................................................ 23 Keywords are special only after a ; or newline, after
Options To test ................................................... 21 another keyword, and in certain other contexts.
Patterns ............................................................... 9 pat − a bash pattern. See Patterns.
Pre-Defined Variables ........................................ 10
Process Substitution .......................................... 8 pipeline − a command or multiple commands connected
Prompting ........................................................... 4 by a pipe (|).
Quoting ............................................................... 6 string − a collection of characters treated as a unit.
Readline .............................................................. 25 substitution − the process of replacing parts of the
Readline Directives ............................................ 25 command line with different text, e.g., replacing a
Readline Key Bindings ....................................... 25 variable with its value. bash performs many
Readline Variables .............................................. 26 substitutions. This card lists them in the order they are
Restricted bash................................................... 2 performed.
Signals and Traps ............................................... 13
Special Characters.............................................. 24 word − a generic argument; a word. Quoting may be
Tilde Substitution ............................................... 6 necessary if it contains special characters.
Variable Assignment.......................................... 9
Variable Names .................................................. 9 RESTRICTED bash
Variable Substitution ......................................... 7 If bash is invoked as rbash, or with the −r option, it is
restricted. The following actions are not allowed in a
This reference card was written by Arnold Robbins. We restricted shell:
thank Chet Ramey (bash’s maintainer) for his help.
changing directory with cd
setting or unsetting $SHELL or $PATH
OTHER SSC PRODUCTS: using path names for commands that contain /
using a path name that contains / for the . command
Specialized Systems Consultants, Inc. importing functions from the environment
(206)FOR-UNIX/(206)782-7733 parsing $SHELLOPTS at startup
FAX: (206)782-7191 redirecting output with any of >, >|, <>, >&, &>, or >>
using exec to run a different command
E-mail: [email protected] adding or deleting built-in commands with enable
URL: http://www.ssc.com using command −p to bypass a restricted $PATH
using set +r or set +o restricted
Linux Journal—The Premier Linux Magazine These restrictions are in effect after executing all
Technical Books and CDs startup files, allowing the author of the startup files full
control in setting up the restricted environment. (In
SAMBA: Integrating UNIX and Windows practice, restricted shells are not used much, as they
Shell Tutorials, KSH Reference are difficult to set up correctly.)
VI & Emacs References, VI Tutorial
Error Reporting
If you find an error in this reference and are the first to
© Copyright 1999 Specialized Systems Consultants, Inc., report it, we will send you a free copy of any of our
P.O. Box 55549, Seattle, WA 98155-0549. references. Please write, or send electronic mail to
All Rights Reserved. [email protected].
1 2

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


COMMAND LINE ARGUMENTS INVOCATION AND STARTUP (continued)
bash accepts the one letter options to set, and the 3. Invoked as sh: Interactive login shells read and
additional one letter and GNU-style long options shown execute /etc/profile and ˜/.profile if they exist. These
below. files are skipped if −−noprofile is used. Interactive
shells expand $ENV and execute that file if it exists.
$ bash [options] [args]
Non-interactive shells do not read any startup files.
− ends option processing
After the startup files are executed, bash enters POSIX
−− ends option processing
mode.
−c cmd execute cmd (default reads
command from file named in 4. POSIX mode: When started with −−posix, interactive
first entry of args and found via shells expand $ENV and execute the given file. No
path search) other startup files are read.
−D print all double quoted strings
5. Invoked via rshd: If run from rshd and not invoked as
that are preceded by a $ to
sh, bash reads ˜/.bashrc. The −−norc option skips this
stdout. This implies −n, no
step, and the −−rcfile option changes the file, but rshd
commands are executed
usually does not pass these options on to the shell it
−i set interactive mode
invokes.
−r set restricted mode
−s read commands from stdin If $SHELLOPTS exists in the environment at startup,
(default) bash enables the given options.
−−dump−po−strings same as −D, but output in GNU
gettext format
−−dump−strings same as −D PROMPTING
−−help display a help message and exit When interactive, bash displays the primary and
successfully secondary prompt strings, $PS1 and $PS2. bash
−−login act like a login shell expands the following escape sequences in the values
−−noediting do not use the readline library of these strings.
to read commands when \a an ASCII BEL character (octal 07)
interactive \d the date in ‘‘Weekday Month Day’’ format
−−noprofile do not read any of the \e an ASCII escape character (octal 033)
initialization files. See \h the hostname up to the first dot (.)
Invocation And Startup, below \H the full hostname
−−norc do not read ˜/.bashrc if \n a newline
interactive. See Invocation And \r a carriage return
Star tup, below \s the name of the shell (basename of $0)
−−posix follow the IEEE POSIX 1003.2 \t the time in 24-hour HH:MM:SS format
standard \T the time in 12-hour HH:MM:SS format
−−rcfile file use file instead of ˜/.bashrc if \u the user’s username
interactive \v the version of bash (e.g., 2.02)
−−restricted same as −r \V the version and patchlevel of bash (e.g., 2.02.0)
−−verbose same as set −v \w the current working directory
−−version print version information on \W the basename of the current working directory
stdout and exit successfully \! the history number of this command
\# the command number of this command
INVOCATION AND STARTUP \$ a # if the effective UID is 0, otherwise a $
There are five ways that bash runs: normal interactive, \@ the time in 12-hour am/pm format
normal non-interactive, as sh, in POSIX mode, or \\ a backslash
invoked via rshd. \nnn the character corresponding to octal value nnn
\[ start a sequence of non-printing characters
1. Normal interactive: Login shells run commands in \] end a sequence of non-printing characters
/etc/profile. The first of ˜/.bash_profile, ˜/.bash_login,
and ˜/.profile that is found is executed. This stage is The history number is the number of the command in
skipped if −−noprofile is used. the history list, which may include commands restored
from the history file. The command number is the
Upon logout, bash runs ˜/.bash_logout if it exists. number of this command starting from the first
Interactive non-login shells execute ˜/.bashrc, if it command run by the current invocation of the shell.
exists. The −−rcfile ifile option changes the file that is The default value of PS1 is ‘‘\s−\v\$ ’’.
used.
2. Normal non-interactive: Non-interactive shells do
variable, command, and arithmetic substitution on the
value of $BASH_ENV, and if the result names an
existing file, that file is executed.

3 4

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


HISTORY SUBSTITUTION QUOTING
History expansion is similar to csh’s. It is enabled by \c quote single character c
default in interactive shells. History expansion `...` old style command substitution
happens before the shell breaks the input into words, "..." text treated as a single argument, double
although quoting is recognized and quoted text is quotes removed; variable, command and
treated as one history ‘‘word’’. arithmetic substitutions performed;
use \ to quote $, \, `, and "
History substitution is performed on history events,
$"..." like "...", but locale translation done
which consist of an event designator (which previous line
´...´ text treated as a single argument, single
to start with), a word designator (which word from that
quotes removed; text between quotes
line to use, starting with zero), and one or more
left alone, cannot include ´
optional modifiers (which parts of the words to use).
$´...´ text treated as a single argument, $ and
Colons separate the three parts, although the colon
single quotes removed; no substitutions
between the event designator and word designator
performed; ANSI C and additional
may be omitted when the word designator begins with
escape sequences processed:
ˆ, $, *, −, or %. Each modifier is separated from the next
one with a colon. The histchars variable specifies the \a alert (bell) \v vertical tab
start-of-history and quick substitution characters, and \b backspace \ddd octal value ddd
also the comment character that indicates that the rest \f form feed \xhhh hex value hhh
of a line is a comment. The previous command is the \n newline \\ backslash
default event if no event designator is supplied. \r carriage return \e escape, not in ANSI C
\t horizontal tab
The event designators are:
! start a history substitution
!n command line n ALIASING
!−n current line minus n (n previous) alias name=value ...
!! the previous command Aliases are expanded when a command is read, not
!str most recent command line starting with when executed. Alias names can contain any non-
str special character, not just alphanumerics, except for =.
!?str[?] most recent command line containing str Alias expansion is done on the first word of a command.
!# the entire command line typed so far If the last character of the replacement text is a blank,
ˆoldˆnewˆ quick substitution: repeat last command then the next word in the command line is checked for
changing old to new alias expansion. Aliases can even be used to redefine
The word designators are: shell keywords, but not in POSIX mode.
0 the zero’th word (command name)
n word n BRACE EXPANSION
ˆ the first argument, i.e., word one Brace expansion is similar to csh’s. A word must
$ the last argument contain at least one unquoted left brace and comma to
% the word matched by the most recent be expanded. bash expands the comma-separated
!?str? search items in order, the result is not sorted. Brace
x−y words x through y. −y is short for 0−y expansions may be nested. For example:
* words 1 through the last (like 1−$)
n* words n through the last (like n−$) $ mkdir /usr/{gnu,local}/{src,bin,lib}
n− words n through the next to last
The modifiers are: TILDE SUBSTITUTION
e remove all but the suffix of a filename ˜ substitute $HOME
g make changes globally, use with s ˜user substitute user’s home directory
modifier, below ˜+ substitute $PWD
h remove the last part of a filename, ˜− substitute $OLDPWD
leaving the ‘‘head’’ ˜n substitute ${DIRSTACK[n]}. A leading +
p print the command but do not execute it or − is allowed: negative values count
q quote the generated text from the end of the stack
r remove the last suffix of a filename Tilde substitution happens after alias expansion. It is
s/old/new/ substitute new for old in the text. Any done for words that begin with ˜ and for variable
delimiter may be used. An & in the assignment.
replacement means the value of old. With
empty old, use last old, or the most recent In variable assignments, it is also done after a : in the
!?str? search if there was no previous old value. Tilde substitution is done as part of word
t remove all but the last part of a filename, expansion. This means for ${name op word}, word will be
leaving the ‘‘tail’’ checked for tilde substitution, but only if the operation
x quote the generated text, but break into requires the value of the right-hand side.
words at blanks and newline
& repeat the last substitution

5 6

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


VARIABLE SUBSTITUTION ARITHMETIC EVALUATION
$name reference to shell variable name Arithmetic evaluation is done with the let built-in
$ {name } use braces to delimit shell variable name command, the ((...)) command and the $((...))
$ {name − word } expansion for producing the result of an expression.
use variable name if set, else use word
All arithmetic uses long integers. Use typeset −i to get
$ {name = word }
integer variables. Integer constants look like [base#]n
as above but also set name to word
where base is a decimal number between two and 64,
$ {name ? word }
and n is in that base. The digits are 0-9, a-z, A-Z, _ and
use name if set, otherwise print word and
@. A leading 0 or 0x denote octal or hexadecimal.
exit (interactive shells do not exit)
$ {name + word } The following operators based on C, with the same
use word if name is set, otherwise use precedence and associativity, are available.
nothing
+ − unary plus and minus
${name[n] } element n in array name
! ˜ logical and bitwise negation
${#name} length of shell variable name
** exponentiation (not in C)
${#name[*] } number of elements in array name
* / % multiply, divide, modulus
${#name[@] } number of elements in array name
+ − addition, subtraction
${name#pat} remove shortest leading substring
<< >> left shift, right shift
of name that matches pat
< <= > >= comparisons
${name##pat} remove longest leading substring
== != equals, not equals
of name that matches pat
& bitwise AND
${name%pat} remove shortest trailing substring
ˆ bitwise XOR
of name that matches pat
| bitwise OR
${name%%pat}
&& logical AND, short circuit
remove longest trailing substring
|| logical OR, short circuit
of name that matches pat
?: in-line conditional
${name:start}
= += −= *= /= %= &= |= ˆ= <<= >>=
${name:start:length}
assignment operators
length characters of name starting at
start (counting from 0); use rest of Inside let, ((...)), and $((...)), variable names do not need
value if no length. Negative start a $ to get their values.
counts from the end. If name is * or @
or an array indexed by * or @, start COMMAND SUBSTITUTION
and length indicate the array index and $(command) new form
count of elements. start and length can `command` old form
be arithmetic expressions
${name/pattern/string} Run command, substitute the results as arguments.
value of name with first match of pattern Trailing newlines are removed. Characters in $IFS
replaced with string separate words (see Field Splitting). The new form is
${name/pattern} preferred for simpler quoting rules.
value of name with first match of pattern $((expression)) arithmetic substitution
deleted
${name//pattern/string} The expression is evaluated, and the result is used as an
value of name with every match of argument to the current command.
pattern replaced with string
${name/#pattern/string} PROCESS SUBSTITUTION
value of name with match of pattern cmd <(list1) >(list2)
replaced with string; match must occur
at beginning Runs list1 and list2 asynchronously, with stdin and
${name/%pattern/string} stdout respectively connected via pipes using fifos or
value of name with match of pattern files in /dev/fd. These file names become arguments to
replaced with string; match occurs at end cmd, which expects to read its first argument and write
its second. This only works if you have /dev/fd or fifos.
Note: for −, =, ?, and +, using name: instead of name
tests whether name is set and non-NULL; using name
tests only whether name is set.
FIELD SPLITTING
Quoted text becomes one word. Otherwise,
For #, ##, %, %%, /, //, /#, and /%, when name is * or @ occurrences of any character in $IFS separate words.
or an array indexed by * or @, the substring or Multiple whitespace characters that are in $IFS do not
substitution operation is applied to each element. delimit empty words, while multiple non-whitespace
characters do. When $IFS is not the default value,
sequences of leading and trailing $IFS whitespace
characters are removed, and printable characters in
$IFS surrounded by adjacent $IFS whitespace
characters delimit fields. If $IFS is NULL, bash does
not do field splitting.
7 8

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


PATTERNS PRE-DEFINED VARIABLES
? match single character in filename $n use positional parameter n, n ≤ 9
* match 0 or more characters in filename ${n} use positional parameter n
[chars ] match any of chars $* all positional parameters
(pair separated by a − matches a range) $@ all positional parameters
[!chars ] match any except chars "$*" equivalent to "$1 $2 ..."
[ˆchars ] match any except chars "$@" equivalent to "$1" "$2" ...
$# number of positional parameters
If the extglob option to shopt is set, the following
$− options to shell or by set
extended matching facilities may be used.
$? value returned by last command
?(pat-list) optionally match any of the patterns $$ process number of current shell
*(pat-list) match 0 or more of any of the patterns $! process number of last background
+(pat-list) match 1 or more of any of the patterns cmd
@(pat-list) match exactly 1 of any of the patterns $_ name of program in environment at
!(pat-list) match anything but any of the patterns startup. Value of last positional
argument in last command. Name of
pat-list is a list of one or more patterns separated by |.
changed mail file in $MAILPATH
The POSIX [[=c=]] and [[.c.]] notations for same-weight $auto_resume enables use of single-word
characters and collating elements are accepted. The commands to match stopped jobs for
notation [[:class:]] defines character classes: foregrounding. With a value of exact,
the word must exactly match the
alnum alphanumeric lower lower-case
command used to start the job. With
alpha alphabetic print printable
a value of substring, the typed word
blank space or tab punct punctuation
can be a substring of the command,
cntrl control space whitespace
like %?string
digit decimal upper upper-case
$BASH full file name used to invoke bash
graph non-spaces xdigit hexadecimal
$BASH_ENV in normal non-interactive shells only,
Three shopt options affect pattern matching. value is variable, command and
arithmetic substituted for path of
dotglob include files whose names begin with .
startup file (See Invocation And
nocaseglob ignore case when matching
Star tup)
nullglob remove patterns that don’t match
$BASH_VERSION the version of bash
When expanding filenames, . and .. are ignored, $BASH_VERSINFO[0] the major version number
filenames matching the patterns in $GLOBIGNORE are (release)
also ignored and a leading . must be supplied in the $BASH_VERSINFO[1] the minor version number
pattern to match filenames that begin with . . (version)
However, setting GLOBIGNORE enables the dotglob $BASH_VERSINFO[2] the patchlevel
option. Include .* in GLOBIGNORE to get the default $BASH_VERSINFO[3] the build version
behavior. $BASH_VERSINFO[4] the release status
$BASH_VERSINFO[5] same as $MACHTYPE
VARIABLE NAMES $CDPATH search path for cd command
Variable names are made up of letters, digits and $DIRSTACK[*] array variable containing the pushd
underscores. They may not start with a digit. There is and popd directory stack
no limit on the length of a variable name, and the case $ENV in interactive POSIX mode shells, or
of letters is significant. when invoked as sh, value is variable,
command and arithmetic substituted
for path of startup file
VARIABLE ASSIGNMENT $EUID the effective user id (readonly)
Assignments to integer variables undergo arithmetic
$FCEDIT default editor for the fc command (no
evaluation. Variable assignments have one of the
default value)
following forms.
$FIGNORE colon-separated list of suffixes giving
name = word set name to word the set of filenames to ignore when
name[index] = word doing filename completion using
set element index of array name to word readline
name =( word ...) $GLOBIGNORE colon-separated list of patterns giving
set indexed array name to words the set of filenames to ignore when
name =( [num]=word ...) doing pattern matching
set given indices of array name to words $GROUPS[*] readonly array variable with the list
of groups the user belongs to
$histchars characters that control csh-style
history (default: !ˆ#). See Histor y
Substitution

9 10

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


PRE-DEFINED VARIABLES (continued) PRE-DEFINED VARIABLES (continued)
$HISTCMD history number of the current $OSTYPE string describing the
command operating system running
$HISTCONTROL with a value of ignorespace, do not bash
enter lines that begin with spaces $PATH command search path
into the history file. With a value of $PIPESTATUS[*] array variable containing exit
ignoredups, do not enter a line that status values from processes
matches the previous line. Use in the most recently executed
ignoreboth to combine both options foreground pipeline
$HISTFILE where command history is stored $PPID process id of shell’s parent
$HISTFILESIZE maximum number of lines to keep in $PROMPT_COMMAND command to run before each
$HISTFILE primary prompt
$HISTIGNORE colon-separated list of patterns; if the $PS1 primary prompt string
current line matches any of them, the (\s−\v\$)
line is not entered in the history file. $PS2 secondary prompt string (>)
& represents the last history line. $PS3 select command prompt
Patterns must match the whole line string (#?)
$HISTSIZE number of previous commands to $PS4 tracing prompt string (+)
keep available while bash is running $PWD current working directory
$HOME home directory for cd command and $RANDOM set each time it’s referenced,
value used for tilde expansion 0 − 32767
$HOSTFILE file in format of /etc/hosts to use for $REPLY set by the select and read
hostname completion commands
$HOSTNAME name of the current host $SECONDS number of seconds since shell
$HOSTTYPE string describing the current host invocation
$IFS field separators (space, tab, newline) $SHELL name of this shell
$IGNOREEOF for interactive shells, the number of $SHELLOPTS colon-separated list of the
consecutive EOFs that must be enabled shell options for set
entered before bash actually exits −o
$INPUTRC name of readline startup file, $SHLVL incremented by one for each
overrides ˜/.inputrc sub-bash
$LANG name of current locale $TIMEFORMAT format string for output of
$LC_ALL current locale; overrides $LANG and time keyword. Special
other $LC_ variables constructs introduced by %.
$LC_COLLATE current locale for character collation, %[p][l]R elapsed secs
includes sorting results of filename %[p][l]U user CPU secs
expansion %[p][l]S system CPU secs
$LC_CTYPE current locale for character class %P CPU percentage
functions (see Patterns) %% literal %
$LC_MESSAGES current locale for translating $"..."
strings Optional p gives the precision,
$LINENO line number of line being executed in the number of digits after the
script or function decimal point; it must be
$MACHTYPE a string in GNU cpu-company-system between 0 and 3. Optional l
format describing the machine produces a longer format, in
running bash the form MMmSS.FFs
$MAIL name of a mail file, if any $TMOUT number of seconds to wait
$MAILCHECK check for mail every n seconds (60 during prompt before
default) terminating
$MAILPATH filenames to check for new mail; uses $UID the real user id (readonly)
: separator; filename may be followed
by ?message; $_ in message is
matched mail file name. Overrides
FUNCTIONS
Functions run in the same process as the calling script,
$MAIL
and share the open files and current directory. They
$OLDPWD previous working directory
access their parameters like a script, via $1, $2 and so
$OPTARG value of last argument processed by
on. $0 does not change. return may be used inside a
getopts
function or . script. Functions share traps with the
$OPTERR if set to 1, display error messages
parent script, except for DEBUG. Functions may be
from getopts (default: 1)
recursive, and may have local variables, declared using
$OPTIND index of last argument processed by
declare, local, or typeset. Functions may be exported
getopts
into the environment with export −f.

11 12

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


INPUT/OUTPUT CONTROL COMMANDS
Redirections are done left to right, after pipes are set ! pipeline
up. Default file descriptors are stdin and stdout. File execute pipeline. If exit status was non-zero, exit
descriptors above 2 are marked close-on-exec. zero. If exit status was zero, exit 1
case word in [[(]pat 1[|pat 2 ]...) list ;; ]... esac
&>word send stdout and stderr to word
execute list associated with pat that matches word.
>&word send stdout and stderr to word
Field splitting is not done for word. pat is a bash
[n]<file use file for input
pattern (see Patterns). | is used to indicate an OR
[n]>file use file for output
condition. Use leading ( if case is inside $( )
[n]>|file like >, but overrides noclobber
for name [in words] ; do list ; done
[n]>>file like > but append to file if it exists
sequentially assign each word to name and execute
[n]<>file open file for read/write (default: fd0)
list. If in words is missing use the positional
[n]<&m duplicate input file descriptor from m
parameters
[n]>&m duplicate output file descriptor from m
[function] func ( ) { list ; }
[n]<&− close input file descriptor
define function func, body is list (see Functions)
[n]>&− close output file descriptor
if list1; then list2 [; elif list3 ; then list4]...[; else list5] ; fi
[n]<<word
if executing list1 returns successful exit status,
input comes from the shell script; treat a line with
execute list2 else ...
word as EOF on input. If any of word is quoted, no
select name [in words] ; do list ; done
additional processing is done on input by the shell.
print a menu of words, prompt with $PS3 and read a
Otherwise:
line from stdin, saving it in $REPLY. If the line is
• do variable, command, arithmetic substitutions
the number of one of the words, set name to it,
• ignore escaped newlines
otherwise set name to NULL. Execute list. If in
• use \ to quote \, $, `, and first character of word
words is missing use the positional parameters.
[n]<<− word as above, but with leading tabs ignored
bash automatically reprints the menu at the end of
Of &> and >&, the first is preferred. It is equivalent to the loop
>word 2>&1. time [−p] pipeline
execute pipeline; print elapsed, system and user
times on stderr.
EXECUTION ORDER −p print times in POSIX format
All substitutions and I/O redirections are performed The $TIMEFORMAT variable controls the format of
before a command is actually executed. the output if −p is not used. bash uses the value
bash maintains an internal hash table for caching $’\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS’ if there is
external commands. Initially, this table is empty. As no value for $TIMEFORMAT
commands are found by searching the directories listed until list 1 ; do list 2 ; done
in $PATH, they are added to the hash table. like while but negate the termination test
while list 1 ; do list 2 ; done
The command search order is shell functions first, built- execute list 1. If last command in list 1 had a
in commands second, and external commands (first in successful exit status, execute list 2 followed by
the internal hash table, and then via $PATH) third. list 1. Repeat until last command in list 1 returns an
unsuccessful exit status
SIGNALS AND TRAPS ((...))
Signal handling is done with the trap built-in command. arithmetic evaluation, like let "..."
The word argument describing code to execute upon [[expression]]
receipt of the signal is scanned twice by bash; once evaluate expression, return successful exit status if
when the trap command is executed, and again when true, unsuccessful if false (see Conditional
the signal is caught. Therefore it is best to use single Expressions for details)
quotes for the trap command. Traps are executed in ( list )
order of signal number. You cannot change the status execute list in a sub-shell
of a signal that was ignored when the shell started up. { list ; }
execute list in the current shell
Traps on DEBUG happen after commands are executed.
Backgrounded commands (those followed by &) will
ignore the SIGINT and SIGQUIT signals if the monitor
option is turned off. Otherwise, they inherit the values
of the parent bash.

ARRAYS
Arrays in bash have no limits on the number of
elements. Array indices start at 0. Array subscripts
can be arithmetic expressions. Array elements need
not be contiguous. bash does not have associative
arrays.

13 14

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


CONDITIONAL EXPRESSIONS BUILT-IN COMMANDS
Used with the [[...]] compound command, which does These commands are executed directly by the shell.
not do pattern expansion or word splitting. Almost all accept −− to mark the end of options.
string true if string is not NULL . file
−a file true if file exists (−e is preferred) source file
−b file true if file is a block device read and execute commands from file. If
−c file true if file is a character device arguments, save and restore positional params.
−d file true if file is a directory Search $PATH; if nothing found, look in the current
−e file true if file exists directory
−f file true if file is a regular file : null command; returns 0 exit status
−g file true if file has setgid bit set [ see test
−G file true if file group is effective gid alias [−p] [name[=value] ...]
−h file true if file is a symbolic link create an alias. With no arguments, print all
−k file true if file has sticky bit set aliases. With name, print alias value for name
−L file true if file is a symbolic link −p print alias before each alias
−n string true if string has non-zero length bg [jobid]
−N file true if file exists and was modified since put jobid in the background
last read bind [−m map] [−lpPsSvV]
−o option true if option is on bind [−m map] [−q func] [−r keyseq] [−u func]
−O file true if file owner is effective uid bind [−m map] −f file
−p file true if file is a fifo (named pipe) bind [−m map] keyseq:func
−r file true if file is readable display and/or modify readline function and key
−s file true if file has non-zero size bindings. The syntax is same as for ˜/.inputrc
−S file true if file is a socket −f file read new bindings from file
−t filedes true if filedes is a terminal −l list the names of all readline functions
−u file true if file has setuid bit set −m map use the keymap map
−w file true if file is writable −p list readline functions and bindings
−x file true if file is executable for re-reading
−z string true if string has zero length −P list readline functions and bindings
file1 −nt file2 true if file1 is newer than file2 or file2 −q func show which keys invoke func
does not exist −r keyseq remove bindings for keyseq
file1 −ot file2 true if file1 is older than file2 or file2 −s list readline key sequences and macros
does not exist for re-reading
file1 −ef file2 true if file1 and file2 are the same file −S list readline key sequences and macros
string == pattern −u func remove key bindings for func
true if string matches pattern −v list readline variable names and values
string != pattern for re-reading
true if string does not match pattern −V list readline variable names and values
string1 < string2 break [n]
true if string1 is before string2 exit from enclosing for, while, until or select loop.
string1 > string2 If n is supplied, exit from n’th enclosing loop
true if string1 is after string2 builtin shell-builtin [ args ...]
exp1 −eq exp2 true if exp1 equals exp2 execute shell-builtin with given args and return
exp1 −ne exp2 true if exp1 does not equal exp2 status. Useful for the body of a shell function that
exp1 −lt exp2 true if exp1 is less than exp2 redefines a built-in, e.g., cd
exp1 −gt exp2 true if exp1 is greater than exp2 cd [−LP] [dir]
exp1 −le exp2 true if exp1 is less than or equal to exp2 change current directory to dir ($HOME default).
exp1 −ge exp2 true if exp1 is greater than or Do directory path search using value of $CDPATH
equal to exp2 −L use logical path for cd .., $PWD (default)
(expression) true if expression is true, for grouping −P use physical path for cd .., $PWD
! expression true if expression is false If both are given, the last one on the command line
exp1 && exp2 true if exp1 AND exp2 are true wins
exp1 | | exp2 true if exp1 OR exp2 is true cd [−LP] −
change current directory to $OLDPWD
If file is /dev/fd/n, then, if there is no /dev/fd directory,
command [−pvV] name [arg ...]
file descriptor n is checked. Otherwise, the real
without −v or −V, execute name with arguments arg
/dev/fd/n file is checked. Linux, FreeBSD, BSD/OS (and
−p use a default search path, not $PATH
maybe others) return info for the indicated file
−v print a one word description of name
descriptor, instead of the actual /dev/fd device file.
−V print a verbose description of name
Both && and || are short circuit. Operands of continue [n]
comparison operators undergo arithmetic evaluation. do next iteration of enclosing for, while, until or
For == and !=, quote any part of pattern to treat it as a select loop. If n is supplied, iterate n’th enclosing
string. loop

15 16

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


BUILT-IN COMMANDS (continued) BUILT-IN COMMANDS (continued)
declare [±afFirx] [−p] [name[=value]] export [−fnp] [name[=value] ...]
typeset [±afFirx] [−p] [name[=value]] with no arguments, print names and values of
set attributes and values of variables. Inside exported variables. Otherwise, export names to the
functions, create new copies of the variables. Using environment of commands
+ instead of − turns attributes off. With no names −f names refer to functions
or attributes, print every variable’s name and −n stop exporting each name
attributes −p print export before each variable
−a name is an array fc [−e editor][−nlr][first [last]]
−f each name is a function print a range of commands from first to last from last
−F don’t show function definitions (bodies) $HISTSIZE commands
−i name is an integer; arithmetic −e run editor if supplied; if not, use first of
evaluation is done upon assignment $FCEDIT, $EDITOR, or vi on
−r mark names readonly commands; execute result(s)
−x mark names for export −l list on standard output instead of editing
dirs [−clpv] [+n] [−n] −n don’t print line numbers
display the directory stack −r reverse order of commands
+n show n’th entry from left, n ≥ 0 fc −s [old=new] [command]
−n show n’th entry from right, n ≥ 0 substitute new for old in command (or last command
−c clear the directory stack if no command) and execute the result
−l print a longer format listing fg [jobid]
−p print the stack one entry per line put jobid in the foreground
−v print the stack one entry per line, with getopts optstring name [arg ...]
index numbers parse parameters and options (see bash(1))
disown [−ar] [−h] [job ...] hash [−r] [−p file] [name]
with no options, remove named jobs from the table with no arguments, print the hash table contents,
of active jobs giving hit count and file name
−a remove or mark (with −h) all jobs −p file enter file for name in the hash table
−h mark each job to not receive a SIGHUP −r clear the internal hash table
when bash terminates Assignment to $PATH also clears the hash table
−r use with −h to mark just running jobs help [pattern]
echo [−eEn] [words] print help. With pattern, print help about all the
echo words; −− is not special commands that match pattern
−e expand \-escapes (see echo(1)) history [n]
−E never expand \-escapes history −anrw [file]
−n don’t output trailing newline history [−c]
printf is more portable history −p arg [...]
enable [−adnps] [−f file] [name ...] history −s arg [...]
enable and disable shell built-ins, or load and with no options, print the command history. An
unload new built-ins from shared library files. argument of n prints only n lines. If supplied, use
Disabling a built-in allows use of a disk file with the file instead of $HISTFILE
same name as a built-in −a append new history lines to history file
−a print all built-ins, with their status −c clear the history list
−d delete a built-in loaded with −f −n read new history lines in the file into the
−f file load a new built-in name from file internal history list
−n disable name, or print disabled built-ins −p perform history substitution and print
with no names the results
−p print enabled built-ins −r replace internal history with contents of
−s print only POSIX special built-ins history file
eval [words] −s place the args into the history list
evaluate words and execute result for later use
exec [−a name] [−cl] [words] −w write the internal history to the file
execute words in place of the shell. If redirections jobs [−lnprs] [jobid ...]
only, change the shell’s open files jobs −x command [args ...]
−a use name for argv[0] list information about jobs
−c clear the environment first −l also list process id
−l place a − on argv[0] (like login(1)) −n only list stopped or exited jobs
If the exec fails, non-interactive shells exit, unless −p only list process groups
the shopt option execfail is set −r only list running jobs
exit [n] −s only list stopped jobs
exit with return value n. Use $? if no n −x replace any jobid in the command line
with the corresponding process group ID,
and execute the command

17 18

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


BUILT-IN COMMANDS (continued) BUILT-IN COMMANDS (continued)
kill [−sig] jobid ... readonly [−afp] [name=value ...]
kill [−s signame] [−n signum] jobid ... mark names read-only; print list if no names
send SIGTERM or given signal to named jobids. −a each name must be an array
Signals are names listed in /usr/include/signal.h −f each name must be a function
with or without the prefix ‘‘SIG’’. Stopped jobs get −p print readonly before each variable
a SIGCONT first if sig is either SIGTERM or return [n]
SIGHUP exit function or . script with return value n. With no
kill −l [sigs ...] n, return status of last command. If not in function
list signal names and/or numbers. If sig is a or . script, print an error message
numerical exit status, print the signal that killed the set [−options] [−o option] [words]
process set flags and options (see Options To set). words set
let arg ... positional parameters
evaluate each arg as an arithmetic expression; exit 0 set [+options] [+o option] [words]
if the last expression was non-zero, 1 otherwise unset flags and options
(see Arithmetic Evaluation) shift [n]
local [name[=value] ...] rename positional parameters; $n+1=$1 ...
create variables with the given values local to a n defaults to 1
function. With no operands, print a list of local shopt [−opqsu] [option ...]
variables. Must be used inside a function print or change values of shell options. With no
logout arguments, print shell option information
exit a login shell −o only change set −o options
popd [−n] [+n] [−n] −p print settings for re-reading
remove entries from the directory stack. With no −q quiet mode; exit status indicates
arguments, remove the top entry and cd there option status
+n remove n’th entry from left, n ≥ 0 −s set (enable) given option; with no
−n remove n’th entry from right, n ≥ 0 options, print those that are set
−n don’t change directory −u unset (disable) given option; with no
printf format [arg ...] options, print those that are unset
print output like ANSI C printf, with extensions (See Options To shopt)
%b expand escape sequences in strings suspend [−f]
%q print quoted string that can be re-read suspend the shell until SIGCONT is received
Format conversions are reused as needed −f force suspension, even for login shell
pushd [−n] [dir] test
pushd [−n] [+n] [−n] evaluate conditional expressions (see Options To
add an entry to the directory stack. With no test and Conditional Expressions)
arguments, exchange the top two entries times
+n rotate the stack so that the n’th print accumulated process times
entry from left is at the top, n ≥ 0 trap [−lp] [word] [sigs]
−n rotate the stack so that the n’th execute word if signal in sigs received. sigs are
entry from right is at the top, n ≥ 0 numbers or signal names with or without ‘‘SIG’’.
−n don’t change directory With no word or sigs, print traps. With no word,
dir push dir on the stack and cd there reset sigs to entry defaults. If word is ‘‘−’’, reset sigs
pwd [−LP] to entry defaults. If word is the null string, ignore
print working directory name sigs. If sigs is 0 or EXIT, execute word on exit from
−L print logical path (default) shell. If sigs is DEBUG, run word after every
−P print physical path command.
If both are given, the last one on the command line −l print a list of signal names and numbers
wins −p print traps with quoting
read [−a name] [−er] [−p prompt] [names ...] type [−apt] name ...
read stdin and assign to names. $IFS splits input. describe how the shell interprets name
$REPLY is set if no name given. Exit 0 unless end- −a print all possible interpretations
of-file encountered of name
−a read words into indexed array name −p print the name of the file to execute if
−e use readline if reading from a terminal name is an external program
−p print prompt if reading from a terminal −t print a keyword describing name
before reading
−r \ at end of line does not do line
continuation

19 20

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


BUILT-IN COMMANDS (continued) OPTIONS TO set
ulimit [type] [options] [limit] The set command is complicated. Here is a summary.
set or print per-process limits Use + instead of − to turn options off. With no
type (default is both): arguments, set prints the names and values of all
−H hard limit variables.
−S soft limit
set [±abBCefhHkmnpPtuvx] [±o option ...] [arg ...]
options:
−a automatically export variables upon
−a all (display only)
assignment
−c core file size
−b print job completion messages
−d ‘‘k’’ of data segment
immediately, don’t wait for next prompt
−f maximum file size
−B enable brace expansion (default)
−m ‘‘k’’ of physical memory
−C force >| to overwrite for existing files
−n maximum file descriptor + 1
−e exit upon non-zero exit from a command
−p size of pipe buffers
−f disable pattern expansion
−s ‘‘k’’ of stack segment
−h save command locations in the
−t cpu seconds
internal hash table (default)
−u max processes for one user
−H enable !-style history (default)
−v ‘‘k’’ of virtual memory
−k place all variable assignments in
−f is assumed if no options are given. The size for
the environment (obsolete)
−p is in 512-byte blocks; the others are in sizes of
−m run background jobs in their own
1024 bytes
process group, print a message
umask [−pS] [mask]
when they exit; set automatically for
set file creation permissions mask to complement of
interactive shells on job control systems
mask if octal, or symbolic value as in chmod. With
−n read commands without executing them
no arguments, print current mask. An octal mask is
(ignored if interactive)
permissions to remove, a symbolic mask is
−o set options; with no arguments, print
permissions to keep
current settings
−p print output for re-reading
allexport same as −a
−S print current mask in symbolic form
braceexpand same as −B
unalias [−a] [names]
emacs use an emacs-style line
remove aliases names
editor (default)
−a remove all aliases
errexit same as −e
unset [−fv] [names]
hashall same as −h
unset variables names (same as −v)
histexpand same as −H
−f unset functions names
history enable history
−v unset variables names
ignoreeof like IGNOREEOF=10
Unsetting LINENO, MAILCHECK, OPTARG,
keyword same as −k
OPTIND, RANDOM, SECONDS, TMOUT and _
monitor same as −m
removes their special meaning, even if used
noclobber same as −C
afterwards
noexec same as −n
wait [jobid ...]
noglob same as −f
wait for job jobid; if no job, wait for all children
notify same as −b
nounset same as −u
OPTIONS TO test onecmd same as −t
The test command, and its synonym [...], are built-in to physical same as −P
bash. The command accepts all of the options listed in posix obey the POSIX 1003.2
the Conditional Expressions section. However, since it is standard
a command, options and arguments must be quoted to privileged same as −p
get proper behavior, and normal pattern expansion and verbose same as −v
field splitting are done. Parentheses used for grouping vi use a vi-style line editor
must be quoted. Arithmetic expansion is not done for xtrace same as −x
numeric operators, and pattern matching is not done −p don’t read $ENV, do not take shell
for == and !=. test complies with POSIX. functions from environment, and ignore
options in $SHELLOPTS environment
The −a and −o options have the following meanings, variable
instead of the ones listed in Conditional Expressions: −P follow the physical directory structure
−a logical AND for commands that change the directory
−o logical OR −t read and execute one command,
then exit
−u make it an error to substitute an unset
variable
−v print input lines as they’re read

21 22

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


OPTIONS TO set (continued) OPTIONS TO shopt (continued)
−x print commands as they’re executed, lithist
preceded by expanded value of $PS4. if cmdhist is also enabled, save multi-line
Output is quoted for later reuse commands with newlines, not semi-colons
− turn off −v, −x, stop looking for flags; mailwarn
any remaining args set the print a warning message if a file being checked for
positional parameters mail was accessed since the last time it was
−− do not change flags; set positional checked
parameters from argument list; nocaseglob
with no args, unset the positional do a case-insensitive match when expanding
parameters pathnames
nullglob
OPTIONS TO shopt remove patterns that don’t match any file, instead
The shopt command sets or unsets a number of options of leaving them unchanged in the command line
that affect how bash behaves. This section describes promptvars
each option’s effect when enabled. Unless noted, they do parameter expansion on the prompt variables
are all disabled by default. before printing them. Enabled by default
shift_verbose
cdable_vars print an error message when the shift count is
treat an argument to cd that is not a directory as a greater than the number of positional parameters
variable whose value is the directory name sourcepath
cdspell use $PATH to find shell files given to the . and
attempt to correct minor spelling errors in source commands. Enabled by default
arguments to cd. Errors tried are transposed
characters, a missing character or an extra
character. Only obeyed in interactive shells SPECIAL CHARACTERS
checkhash # start of comment; terminated by newline
check that a command in the hash table still exists | (pipe) connects two commands
before trying to execute it. If it doesn’t, search ; command separator
$PATH & run process in background; default stdin
checkwinsize from /dev/null if no job control
check the window size after each command and && only run following command if previous
update $LINES and $COLUMNS command completed successfully
cmdhist || only run following command if previous
attempt to save all lines of a multi-line command in command failed
the history file as one line, for easy re-editing ´ enclose string to be taken literally
dotglob " enclose string to have variable, command
include files whose names begin with . in path and arithmetic substitution only
expansions $( ) in-line command substitution (new style)
execfail ` in-line command substitution (old style)
keep non-interactive shells from exiting when exec ((...)) arithmetic evaluation, like let "..."
fails $((...)) in-line arithmetic evaluation
expand_aliases \ treat following character literally
expand aliases as described in Aliases. Enabled \ newline line continuation
automatically in interactive shells
extglob JOB IDS AND JOB CONTROL
enable the extended pattern matching facilities (see Jobs can be represented as follows:
Patterns)
histappend jobid the job identifier for a job, where:
append the current history to $HISTFILE upon exit, %% current job
instead of overwriting it %+ current job
histreedit %− previous job
if using readline and a history substitution fails, the %?str job uniquely identified by str
user can re-edit the line %n job number n
histverify %pref job whose command line begins
if using readline, load the results of history with pref
substitution into readline for further editing Usually, a process ID may be used instead of a jobid.
hostcomplete Commands that take a jobid use the current job if no
if using readline, attempt host completion on word jobid is supplied.
containing @
huponexit Traps on SIGCHLD execute whenever a job completes.
send SIGHUP to all jobs when bash exits The commands fg and bg are only available on systems
interactive_comments that support job control. This includes Linux, BSD
in interactive shells, a word starting with # starts a systems, System V Release 4, and most UNIX systems.
comment. Enabled by default
23 24

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


READLINE READLINE VARIABLES
The readline library implements command line editing. Variables control different aspects of readline’s
By default, it provides an emacs editing interface, behavior. You set a variable with
although a vi interface is available. readline is
set variable value
initialized either from the file named by $INPUTRC (if
set), or from ˜/.inputrc. In that file, you can use Unless otherwise noted, value should be either On or
conditionals, define key bindings for macros and Off. The descriptions below describe the effect when
functions, and set variables. the variable is On. Default values are shown in
parentheses.
From the bash level, the bind command allows you to
add, remove and change macro and key bindings. bell-style (audible)
There are five input mode map names that control the defines how readline should ring the bell:
action taken for each input character. The map names audible ring the bell
are emacs, emacs-standard, emacs-meta, emacs-ctlx, none never ring the bell
vi, vi-command, and vi-insert. emacs is the same as visible flash the screen
emacs-standard, and vi is the same as vi-command. comment-begin (#)
You choose which editor you prefer with set −o emacs insert this string for readline-insert-comment,
or set −o vi in your ˜/.bashrc file, or at runtime. (bound to M-# in emacs mode and to # in vi mode)
completion-ignore-case (Off)
readline understands the character names DEL, ESC, ignore case when doing completions
LFD, NEWLINE, RET, RETURN, RUBOUT, SPACE, SPC and completion-query-items (100)
TAB. if the number of completion items is less than this
value, place them in the command line. Otherwise,
READLINE DIRECTIVES ask the user if they should be shown
Directives in the .inputrc file provide conditional and convert-meta (On)
include facilities similar to the C preprocessor. treat characters with the eighth bit set as the meta
version of the equivalent seven bit character
$include disable-completion (Off)
include a file, e.g., a system-wide /etc/inputrc file do not do completion
$if editing-mode (emacs)
start a conditional, for terminal or application set the initial editing mode. Possible values are
specific settings. You can test the following: emacs or vi
application= test the application, e.g. bash or gdb enable-keypad (Off)
mode= test the editing mode, emacs or vi attempt to enable the application keypad. This may
term= test the terminal type be needed to make the arrow keys work
The use of application= is optional; e.g., $if Bash expand-tilde (Off)
$else attempt tilde expansion as part of word completion
start the ‘‘else’’ part of a conditional input-meta (Off)
$endif meta-flag (Off)
finish a conditional enable eight bit input. The two variable names are
synonyms
keymap (emacs)
READLINE KEY BINDINGS set the current keymap. See Readline for a list of
Keys bound to a macro place the macro text into the allowed values. The editing-mode variable also
input; keys bound to a function run the function. affects the keymap
You can use these escape sequences in bindings: mark-directories (On)
append a / to completed directory names
\a alert (bell) \r carriage return mark-modified-lines (Off)
\b backspace \t horizontal tab (TAB) place a * at the front of modified history lines
\C− control prefix \v vertical tab output-meta (Off)
\d delete (DEL) \\ backslash print characters with the eighth bit set directly, not
\e escape (ESC) \" literal " as M-x
\f form feed \´ literal ´ print-completions-horizontally (Off)
\M− meta prefix \ddd octal value ddd display completions horizontally, with the matches
\n newline \xhhh hex value hhh sorted alphabetically, instead of vertically down the
Macros and function bindings look like: screen
show-all-if-ambiguous (Off)
macro: key-seq:"text" immediately list words with multiple possible
function: key-seq:function-name completions, instead of ringing the bell
Macros have quoted text on the right of the colon; visible-stats (Off)
functions have function names. A key-seq is either a when listing possible completions, append a
single character or character name (such as Control−o), character that denotes the file’s type
or a quoted string of characters (single or double
quotes). More information about readline can be found on-line at
http://www.ssc.com/ssc/bash.
25 26

Copyright 11-11-98 08:57:31, SSC, Inc. (all)


Copyright 11-11-98 08:57:31, SSC, Inc. (all)

You might also like