alias expansion
| & ; ( ) < > [space] and [tab] which have special meaning.
\ )
' )
" )
\ ) †
echo the value of \$ENVIRONMENTVARIABLE is $ENVIRONMENTVARIABLE
find . -ctime -1 -exec ls {} \;Without the
\ the shell would interpret the ; as the end of the command\ and new-line are ignored ).
` character encloses a command and is not a quoting character.
' preserves their literal values. ( and ) are not considered list delimeters,
> and < are not considered to define redirection,
$ will not cause expansion ) grep command locate lines containing the three characters (@)† use: \, use quotes instead.
" preserves their literal values, with the exception of $ , `, and \ . ( and ) are not considered list delimeters,
> and < are not considered to define redirection,
$ will not cause expansion )
$ indicates parameter expansion
` indicates command substitution.
\$, \`, \", \\, and \newline are treated specially but other occurances of backslash are not.
The backslashes are removed.
Backslashes preceding characters without a special meaning are left unmodified.
A " may be preserved within "s by preceding it with a backslash.
grep locate lines containing use "TITLE" when use:
* and @ have special
meaning within quotes †.
$'string' expands to string, \b | backspace x'08' |
\\ | backslash |
\n | newline x'0A' |
\r | carriage return x'0D' |
\t | horizontal tab x'09' |
\f | form feed x'0C' |
\v | vertical tab x'0B' |
\e | ESCape character x'1B' frequently used to "lead-in" for a terminal specific function (not ANSI C) |
\a | alert (bell) x'07' |
\' | single quote |
\ooo
| the eight-bit character whose value is the octal value ooo |
\xXX
| the eight-bit character whose value is the hexadecimal value XX |
\cc | a control-c character |
\n or \013 or \x0A or \cJ (i.e. ctrl-J )
The result is single-quoted, as if the dollar sign had not been present.
example:
echo $'\a12\bAB'
1AB
beep is sounded, 12 is displayed, a backspace positions at the 2
then the A is placed over the 2, obscuring the 2, then a B is displayed,
resulting in 1AB.
An alternate method is to prevent the shell from processing the \ by escaping it with another \
( i.e. echo \\a12\\bAB ).
echo $'\a' Sounds the alert tone.
$ will
cause the string to be translated according to the current locale, C or POSIX, the dollar sign is ignored. example: echo $LOCALE QQ(_) eh wot?
# causes remaining characters on that line to be ignored. interactive_comments option to the shopt builtin is
enabled†),
blanks, terminated by a control operator†.
total 88 -rwxr-xr-x 1 realger1 realger1 11747 Nov 14 19:47 a.out -rw-r--r-- 1 realger1 realger1 211 Nov 14 19:24 buff.c -rw-r--r-- 1 realger1 realger1 591 Nov 14 19:52 buff.s -rw-r--r-- 1 realger1 realger1 0 Oct 11 17:49 lx drwx------ 2 realger1 realger1 4096 Oct 30 01:42 logs -rw-r--r-- 1 realger1 realger1 0 Oct 13 15:49 lynx.cfg lrwxrwxrwx 1 root root 11 Dec 19 2004 www -> public_html |
Commands may be on a single line seperated by ; or on seperate lines.
; ; are executed sequentially;
the shell waits for each command to terminate. newline.
When a command ends with & & , the
shell executes the command asynchronously in a subshell,
i.e. the shell does not wait for the command to finish, known as executing the command in the background.
The return status is 0 .
The standard input for asynchronous commands is /dev/null in the absence of any explicit redirections.
Pipelines
A sequence of simple commands separated by |†.
Pipelines are one of the most power features of unix shells.
The output of one command is directly input to the next command.
For example to cut the type, mod bit display, links, owner and group columns from the ls -l use:
ls -l | cut -c35-
produces the output:
11747 Nov 14 19:47 a.out
211 Nov 14 19:24 buff.c
591 Nov 14 19:52 buff.s
0 Oct 11 17:49 lx
4096 Oct 30 01:42 logs
0 Oct 13 15:49 lynx.cfg
11 Dec 19 2004 www -> public_html
|
The shell waits for each of the commands in the pipeline to complete, unless the pipeline is to be executed asynchronously † .
Each command in a pipeline is executed in its own subshell †.
The exit status of a pipeline is the exit status of the last command in the pipeline.
If ! precedes
the pipeline, the exit status is the negation of the exit status of the last command.
A list is a sequence of one or more pipelines separated by one
of the operators
; & && ||
terminated by
; & or a newline.
&& and || have equal precedence, followed by
; and & which have equal precedence.
&& AND lists || OR lists.
An AND list has the form: command1 && command2
if command1 returns an exit status of zero; then command2 is executed.
try_to_do_stuff && do_more_stuff_since_it_is_going_well
An OR list has the form: command1 || command2
If command1 returns a non-zero exit status; then command2 is executed.
try_to_do_stuff || clean_up_mess_from_failured_stuff
The return status of AND lists and OR lists is the exit status of the last command executed.
(list) list is executed in a subshell environment (see Command Execution Environment ).( and ) are metacharacters. The return status is the exit status of list.
{ list; }list is executed in the current shell environment and must be terminated with a newline or semicolon. list. { and } are reserved words and must occur
where a reserved word is permitted.list; by whitespace.
((arithmetic_expression))arithmetic_expression is evaluated according to the arithmetic evaluation rules .expression is non-zero, the return status is 0; expression is zero, the return status is non-zerolet expression.
[[ conditional_expression ]] conditional_expression.
== and != string compare operators are used, the
string to the right of the operator is considered a pattern and matched
according to the rules described in Pattern Matching.
For == the return value is 0 if the string matches, 1 otherwise.
For != the return value is 0 if the string does not match, 1 otherwise.
If nocasematch is enabled, the match is performed without regard to the case of alphabetic characters.
Any part of the pattern may be quoted to force it to be matched as a string.
=~ the string to the right of the operator is considered an extended regular expression
and matched as in regex(3)). nocasematch is enabled, the match is performed without regard to the case of alphabetic characters.BASH_REMATCH.BASH_REMATCH[0] is the portion of the string matching the entire regular expression. BASH_REMATCH[n] is the portion of the string matching the nth parenthesized subexpression.
=~, == and != have the same precedence.
( exprn ) | Returns the value of exprn. Used to override the normal precedence of operators or for clarifcation. | ||||||
!exprn | |||||||
conditional operators such as -f† must be unquoted to be recognized as primaries.
for name [ in words ] ; do command-list ; donewords is expanded, generating a list of items.
name is set to each element of this list in
turn, and command-list is executed for each.
in words is omitted, for
executes command-list
once for each positional parameter that is set. words is an empty list, no commands are executed, and the return status is 0!
for ODDNUM in 1 3 5 7 ; do echo $ODDNUM ;done
alternate format:
for (( expr-init ; expr-test ; expr-incr )) ; do command-list ; done
expr-init is evaluated as per arithmetic evaluation.
expr-test is evaluated
| results not 0 | results 0 | |
|---|---|---|
command-list is executed processing continues with | the command after the done.
expr-incr is evaluated and processing continues with the expr-test
|
A 1 is used if an expr is ommited.
The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid.
until while
| until test-commands; do commands; done while test-commands do commands … done As long as | test-commands has an exit status which is
not zero | zero
|
execute | commands
| ||||||||||||||||||
selectively execute the command-list
corresponding to the first pattern that matches word. case
case word in [ [(] pattern1
[… | patternn] )
command-list ;;] … esac
The | is used to separate multiple patterns, and the
) operator terminates a pattern list.
A list of patterns and an
associated command-list is known as a clause.
Each clause must be terminated with ;;.
word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion,
and quote removal before matching is attempted.
pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
There may be an arbitrary number of case clauses, each terminated by a ;;.
The first pattern that matches determines the command-list that is executed.
Example:
|
The code: | |
|
echo "Enter the name of an animal:" read ANIMAL echo "The $ANIMAL has " case $ANIMAL in man | kangaroo ) echo two ;; esac echo "legs."
running code
| Enter the name of an animal: cat The cat has four legs. |
| simple | ||||||
if test; then
true-commands;
more-true-commands; fi
| Frequently written multi line (but wwhy?)if tests | |||||
tests are executed, then upon a return status of
elif list is executed in turn, more-true-commands is executed
If "else false-commands" is present, and the final command in the final if or elif clause has a non-zero exit status,
then false-commands is executed.
The return status is the exit status of the last command executed, or zero if no condition tested true.
if needs space before [
[ x comparison y ] needs spaces around comparison
The very simple (but not as clear)
If first command works, execute second command
./setup.sh && ./process.sh
If first command fails, execute second command
./checkIt || { echo "checkIt failed" ; exit 1; }
(see Lists of Commands )
select name [in words … ]; do commands; done
in
words is omitted, the positional parameters are printed, as
if in "$@" had been specifed.
PS3 prompt is then displayed and a line is read from the standard input.
null.
EOF is read, the select command completes.
The line read is saved in the variable
REPLY.
break or return command is executed, at
which point the select command completes.
select fname in 0.sh birdloger* *.sed ;
do
echo you picked $fname \($REPLY\);
break;
done
1) 0.sh 3) birdloger.pl 5) log-summ.sed
2) birdloger.html 4) birdlogmail2content.sed 6) lslrClean.sed
#? 3
you picked birdloger.pl (3)
Declared using :
[ function ] func () { command-list; }
The reserved word function is optional, if supplied the parentheses are optional.
The command-list is executed when func is specified as the name of a command.
Functions can be defined within a script or in a file but must be defined before they are invoked.
To include a file containing functions use
. fileWithFuncs
funcname arg1 agr3 … no ( ) are used.
When a function is entered, the arguments are the positional parameters.
The number of positional parameters ($#) indicates the number of arguments.
Positional parameter $0 is unchanged.
The exit status of a function is the exit status of the last command executed in the command-list or
the value supplied by return n.
When the function completes, execution resumes with the command after the function call,
the values of the positional parameters and the $# are restored
Variables local to the function may be declared with the local
builtin making them are accessible only to the function and the commands it invokes.
Functions may be recursive. No limit is placed on the number of recursive calls.
Example:
> echo $0notice that
-bash
> cat resetfile.fun
resetfile(){
echo $0
echo $1
if [ -e $1 ]; then rm $1;fi
touch $1
chmod 755 $1
}
> . resetfile.fun
> resetFile output1
-bash$0reflects the caller of the script not the function
output1
>ls -l output1
-rwxr-xr-x 1 me mygroup 0 Oct 7 13:21 0
A parameter is set if it has been assigned a value.
The null string is a valid value.
Once a variable is set, it may be unset only by using the unset builtin.
A variable may be assigned to by a statement of the form
name=[value]
If value is not given, the variable is assigned the null string.
All values undergo tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote removal .
If the variable has its integer attribute set (see declare),
then value is subject to arithmetic expansion even if the $((...)) expansion is not used (see Arithmetic Expansion).
Word splitting is not performed, with the exception of "$@" .
Filename expansion is not performed.
A positional parameter is a parameter denoted by $ and one or more
digits. ($0 is a 'Special' parameter.)
Positional parameters are assigned from the shell's arguments when it is invoked, and
may be reassigned using set , but not with assignment statements.
Positional parameter $N may be referenced as ${N}.
They are temporarily replaced when a function is executed .
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
$* |
|
Before a command is executed, its input and output may be redirected . The redirection operators are < for input and > for output.
While they may precede, appear within or follow a command and are processed from left to right,
are commonly placed after a command where the character's graphic is consistant with the dataflow.
The filename following the redirection operator is subjected to brace, tilde,
parameter, arithmetic and
filename expansion, command substitution and
quote removal.If filename expands to more than one word, Bash reports an error:"ambiguous redirect" and the command is not executed. Redirection opens and closes files for the current shell execution environment. A failure to open or create a file causes the command not to be executed. Since bash processes redirections before invoking the command, sudo will not execute
if the output is redirected to a file that is not writable to the invoking user.
Redirecting Input[n]<filenameRedirection of input causes filename to be opened for reading. Default file descriptor number(n) is 0, standard input. Example: tr '[:upper:]' '[:lower:]' < cedar2.txt
Redirecting Output[n]>[ Redirection of output causes filename to be opened for writing. Example: ls -l > filelist
Default file descriptor Appending Redirected Output[n]>>filename If the file does not exist it is created.
Redirecting both STDOUT and STDERR&>filename
The order of redirections is significant.
directs both standard output and standard error to the file ls -l 2>&1 > /tmp/stdout directs only the standard output to the file , because the standard error was duplicated as standard output before the standard output was redirected .
Redirecting to which will display the STDERR output if there is an error.
|
No parameter expansion, command substitution, filename expansion, or
arithmetic expansion is performed on
duplicates input file descriptors.
moves the file descriptor
moves the file descriptor
Here Documents
Read input from the current source until a line containing only word (with no trailing blanks) is
read.
All of the lines read up to that point are then used as the STDIN for a command.
The format is:
<<[-]word
lines of input
…
word
word.
If any characters in word are quoted, the delimiter is the result of quote
removal on word, and the lines in the here-document are not expanded.
If word is unquoted, all lines of the here-document are subjected to
parameter expansion, command substitution, and arithmetic expansion.
The pair \newline is ignored, and \
must be used to quote the characters \, $, and
`. <<- all leading tab
characters are stripped from input lines and the line containing
delimiter. This allows here-documents within shell scripts to be
indented in a natural fashion.
here is an inpuit line
and another
++++
Duplicating File Descriptors
[n]<&fdes
If n is not specified, the STDIN (file descriptor 0) is used.
If fdes expands to one or more digits, the file descriptor (n) becomes
a copy of that file descriptor.
If the digits in fdes do not specify
a file descriptor open for input, a redirection error occurs.
If fdes evaluates to -, file descriptor n is closed.
[n]>&fdes
duplicates output file descriptors.
If n is not specified, the standard output (file descriptor 1) is used.
If the digits in fdes do not specify a file descriptor open for output, a redirection
error occurs. As a special case, if n is omitted, and
fdes does not expand to one or more digits, STDOUT and
STDERR are redirected .
Moving File Descriptors
The redirection operator[n]<&d-d to file descriptor n, or the standard input
if n is not specified.
d is closed after being duplicated to n.
[n]&d-
d to file descriptor n,
or the standard output ifd is not specified.
Opening File Descriptors for Reading and Writing
[n]<>file
causes file to be opened
for both reading and writing on file descriptor n, or on file
descriptor 0 if n is not specified.
If the file does not exist, it is created.
When a simple command is executed, the shell performs the following operations from left to right.
= in each variable assignment undergoes
tilde expansion, parameter expansion,
command substitution, arithmetic
expansion, and quote removal before being assigned to the variable.
variable=`ls ~/*.sh`
/Users/me > echo $variable
/Users/me/LibraryClean.sh /Users/me/net.sh /Users/me/pocketForCordury.shA
If no command name results, the variable assignments affect the current shell environment.
Otherwise, the variables are added to the environment of the
executed command and do not affect the current shell environment.
If no command name results, redirections are performed, but do not affect the current shell environment.
If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits.
If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.
After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken.
If the command name contains no slashes, the shell attempts to locate it checking for a:
$PATH for a directory containing an executable file. PATH searches (see the description of hash in section Bourne Shell Builtins, this may be a problem if the file is created during the shell execution.
A full search of the directories in $PATH is performed only if the command is not found in the hash table. )&
The status of a simple command is its exit status as provided by the POSIX.1 waitpid function, or
128+n if the command was terminated by signal†??(_) n.
The shell has an execution environment, which consists of :
exec builtin
cd, pushd, or popd, or inherited by the shell at invocation
umask or inherited from the shell's parent
trap
set or inherited from the shell's parent in the environment
set
shopt
aliases
$$, and the value of $PPID When a simple command other than a builtin or shell function is to be executed,(among other things ) it is invoked in a separate execution environment that consists of:
A command invoked in this separate environment cannot affect the calling shell's execution environment.
Command substitution and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation.
Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment.
Changes made to the subshell environment cannot affect the shell's execution environment.
environment, is made available.
On invocation, the shell marks each parameter export to child processes.
Executed commands inherit the environment.
unset,
export and declare add/delete parameters and
functions to/from the environment.
The environment for any simple command or function may be augmented
temporarily by prefixing it with parameter assignments, as described in Shell Parameters.
These assignment statements affect only the environment seen by that command.
With -k (The Set Builtin), all parameter assignments are placed in the environment for a
command, not just those that precede the command name.
When Bash invokes an external command, the variable $_ is set
to the full path name of the command and is included in the environment.
The exit status is used by the Conditional Constructs and some of the list constructs .
All builtins return an exit status of 2 to indicate incorrect usage.
| default keystrokes | see stty
> stty -aintr=^C; quit=^\; kill=^U; eof=^D; eol=<undef> eol2= SIG | QUIT^\ |
If BASH receives a signal, for which a trap has been set, while waiting for a
command to complete, the trap will not be executed until the command completes.
If waiting for an asynchronus command
an exit status greater than 128 is set, then trap is executed.
Commands started by Bash have signal handlers set to the values inherited by the shell from its parent.
-c nor -s is supplied (see Invoking
Bash).
The special parameter $0 is set to the name of the file (rather than the name of the shell),
and the positional parameters are set to the remaining arguments.
When Bash finds such a file in the $PATH for a command, it spawns a subshell to execute it.
In other words, executing
file arguments †
is equivalent to executing
bash file arguments †
This subshell initializes itself, so that the effect is as if a new shell had been invoked
to interpret the script, with the exception that the locations of commands
remembered by the parent (see the description of hash in Bourne Shell Builtins) are retained by the child.
If the first line of a script begins with #!,
the remainder of the line specifies an interpreter for the the script, followed by the arguments.
For example:
#!/usr/bin/perl -w
See chmod regarding setting permissions.