The Bourne Shell - National Cheng Kung University

Download Report

Transcript The Bourne Shell - National Cheng Kung University

The Bourne Shell
吳瑞麟
[email protected]
National Cheng Kung University,
Computer and Network Center
Simple commands
There are three types of commands:
• shell functions,
• built-in commands, and
• normal programs.
The command is searched for (by
name) in that order.
Command list
A list is a sequence of one or more simple
commands or pipelines, separated by ‘ ; ’ ‘&’
‘&&’ ‘ || ’ . With ‘&’ sign , command is
executed in background.
Examples:
$ sync ; sync ; sync ; shutdown now
Conditional Execution
•
With ‘&&’ , command2 is executed only if the
preceding pipeline (or command1) returns a
zero exit status.
command1 && command2
•
With ‘ || ’, command2 is executed only if the
preceding pipeline (or command1) returns a
nonzero exit status.
command1 || command2
The command groups
• Executes list in a sub-shell.
(list)
• List is simply executed ( in current
shell ).
{list;}
The command groups
(cont.)
Examples:
$ pwd
/usr/home/rlwu
$ ( cd wu; pwd )
/usr/home/rlwu/wu
$ pwd
/usr/home/rlwu
$ { echo -n "hello"; echo " world"; } > greeting
Standard devices
• stdin
file descriptor : 0
• stdout file descriptor : 1
• stderr file descriptor : 2
Input/Output redirection
• command < word
Use file word as standard input (file descriptor 0).
• command > word
Use file word as standard output (file descriptor 1). If the file
does not exist it is created; otherwise, it is truncated to zero
length.
• command >>word
Use file word as standard output. If the file exists output is
appended to it (by first seeking to the EOF); otherwise, the
file is created.
Input/Output redirection
(cont.)
• command <&digit
Use the file associated with file descriptor digit as
standard input (file descriptor 0).
• command >&digit
Use the file associated with file descriptor digit as
standard output (file descriptor 1).
Input/Output redirection
(cont.)
If any of the above is preceded by a digit, the file
descriptor which will be associated with the file is that
specified by the digit (instead of the default 0 or 1). For
example :
command 2>&1
associates file descriptor 2 with the file currently
associated with file descriptor 1.
Examples:
$ ( cc a.c 2>&1 ) > log.a
$ command1 2>&1 | command2
here-document
The following redirection is often called a ''here-document''.
command << delimiter
here-doc-text
...
delimiter
All the text on successive lines up to the delimiter is saved
away and made available to the command on standard
input. If the operator is ''<<-'' instead of ''<<'', then leading
tabs in the here-doc-text are stripped.
here-document
(cont.)
Examples:
% cat << eof
? This is the first line.
? This is the second line.
? eof
This is the first line.
This is the second line.
Error Redirection
Any command that produces error messages to stderr
can have those messages redirected to another file.
• Overwrite
• Append
2>
2>>
Examples:
$ cc a.c 2> another_file
$ cc a.c 2>> another_file
Pipeline
• A pipeline is a sequence of one or more
commands separated by `|' .
• The standard output of each command but
the last is connected by a pipe to the
standard input of the next command.
• The exit status of a pipeline is the exit status
of its last command.
command1 | command2 | command3
Comments
A word beginning with # and all the following
characters up to a NEWLINE are ignored. If the first
line in a shell script is #!/bin/xshell the shell
“/bin/xshell” will be invoked to execute the shell script.
Examples:
#!/bin/sh
# This is a comment line
echo Hi!
The if Construction
Syntax:
if list A
then list B
[ elif list C
then
list D ] ...
[ else list E ]
fi
The if Construction
Examples:
# multi-line
if [ -d wu ]
then ls –l wu
fi
#
# single-line
if [ -d wu ] ; then ls –l wu; fi
The case Construction
Used for multi-way branching
Syntax:
case word in
pattern [ | pattern ] ) list A
;;
pattern [ | pattern ]) list B
;;
pattern [ | pattern ]) list N
;;
esac
Pattern Matching
*
Matches any string, including the null string.
?
Matches any single character.
[...] Matches any one of the enclosed characters. A
pair of characters separated by `-' matches any
character lexically between the pair, inclusive. If
the first character following the opening [ is a ! any
character not enclosed is matched.
Examples:
abc)
a??)
a*)
ab | cd)
a* | b?[123])
a[!de]*)
[!a-z]*)
The while Construction
Syntax:
while
list A
do
list B
done
A while command repeatedly executes List A and, if the
return value of the last command in list A is zero,
executes list B ; otherwise the loop terminates.
The while Construction
(cont.)
Examples:
#!/bin/sh
# This is a comment line.
trap "echo bye; exit" 2
while
read A ; [ $A != q -a $A != Q ]
do
echo $A
done
exit
The until Construction
Syntax:
until
list A
do
list B
done
A until command repeatedly executes List A and, if the
return value of the last command in list A is not zero,
executes list B ; otherwise the loop terminates.
The for Construction
Syntax:
for var [ in word list …]
do
list A
done
In which var is any shell variable, and word list is a space delimited
list of strings. Each time a for command is executed, var is set to the
next word taken from the in word list. Execution ends when there are
no more words in the word list.
If in word is omitted, then the for command executes the do list
once for each positional parameter that is set. Execution ends when
there are no more words in the list.
The for Construction
(cont.)
Examples:
#!/bin/sh
#
for AA in $*
do
echo $AA
done
exit
The trap Command
Syntax:
trap 'cmds' signo [signo...]
Description:
Perform cmds upon receipt of signal .
The trap Command(cont.)
Example:
$ cat myprog
#!/bin/sh
# shell script named : “myprog”
trap 'echo bye; exit' 2
while
true
do
echo hello
done
$ myprog
hello
hello
hello
^Cbye
Define a function
Syntax:
name ( )
{
list;
}
Define a function
Examples:
#!/bin/sh
#
trap "echo bye; exit" 2
fn1 ( )
{
for AA in $*
do
echo $AA
done
}
fn1 tom bill john
exit
Special Commands
.
filename
Read and execute commands from
filename and return.
break [ n ]
Exit from the enclosing for or while
loop, if any. If n is specified break n
levels.
continue [ n ]
Resume the next iteration of the
enclosing for or while loop. If n is
specified resume at the n'th
enclosing loop.
Special Commands
exit [ n ]
(cont.)
Exit a shell with the exit status specified
by n. If n is omitted the exit status is that
of the last command executed (an
EOF will also cause the shell to exit.)
export [ name ... ] The given names are marked for
automatic export to the environment of
subsequently-executed commands. If
no arguments are given, variable names
that have been marked for export during
the current shell's execution are listed.
Setting Shell Variables
Syntax:
name=value
*No blanks are allowed in the expression.
Examples:
$ my_name_is=bob
$ MESSAGE=/usr/man/man1/ls.1
$ var5="hello mom"
Show variables
env
Reports the names and values of all
environment variables.
set
Reports the names and values of all shell
variables.
Parameter Substitution
$parameter
or
${parameter}
The braces are required only when parameter is followed
by a letter, digit, or underscore that is not to be
interpreted as part of its name.
Examples:
$ echo $my_name_is
bob
$ echo $MESSY
/usr/man/man1/ls.1
$ more $MESSY
<contents of /usr/man/man1/ls.1>
Parameter Substitution
(cont.)
${parameter:-word}
If parameter is set and is non-null, substitute
its value; otherwise substitute word.
${parameter:=word}
If parameter is not set or is null set it to word;
the value of the parameter is substituted.
Argument parameters may not be assigned to in
this way.
Parameter Substitution
(cont.)
${parameter:?word}
If parameter is set and is non-null, substitute its
value; otherwise, print word and exit from the shell.
${parameter:+word}
If parameter is set and is non-null, substitute word;
otherwise substitute nothing.
If the colon (:) is omitted from the above expressions,
the shell only checks whether parameter is set or not.
Parameter Substitution
Examples:
$ AA="Jonn"
$ CC=""
$ echo ${BB:-Tom}
Tom
$ echo ${CC:-Tom}
Tom
$ echo ${BB-Tom}
Tom
$ echo ${CC-Tom}
* < null >
$ echo ${AA:-Tom}
John
$ echo ${BB:=Tom}
Tom
$ echo $BB
Tom
Command Substitution
The shell executes commands from the string between
two grave accents (``) and the standard output from
these commands may be used as all or part of a word.
Examples:
$ pwd
/usr/home/rlwu
$ AA = `pwd`
$ echo $AA
/usr/home/rlwu
Quoting
• A character may be quoted (made to stand for itself)
by a backslash (\) or a pair of quote marks (' ' or " ").
• All characters enclosed between a pair of single
quotes (' '), except a single quote, are quoted
by the shell.
Examples:
$ aa=1122
$ echo '$aa'
$aa
$ echo ' "$aa" '
"$aa"
Quoting
(Cont.)
• Inside a pair of double quotes (" "), parameter and
command substitution occurs. The backslash
inside double quotes remains literal unless it
precedes the following characters, which it serves to
quote:
$
`
"
\
NEWLINE
Examples:
$ echo " '$aa' is the content of parameter \$aa"
'1122' is the content of parameter $aa
$ echo "`pwd` is the current directory"
/usr/home/rlwu is the current directory
Quoting
(continued)
•A backslash preceding a newline is treated as
a line continuation.
Examples:
$ echo \$ \" \' \\ \`
$" ' \ `
$ echo "This is the first sentence.\
> This is the second sentence.\
> "
This is the first sentence.This is the second
sentence.
Quoting
(cont.)
If $* is within a pair of double quotes, the
arguments are substituted and quoted, separated by
quoted spaces ("$1 $2 ..."); however, if $@ is within
a pair of double quotes, the arguments parameters are
substituted and quoted, separated by unquoted
spaces ("$1" "$2" ... ).
“$*”
“$@”


“$1 $2 …”
“$1” “$2” …
Special variables set by the shell
#
-
?
$
!
The number of arguments in decimal.
Flags supplied to the shell on invocation or
by the set command.
The decimal value returned by the last
synchronously executed command.
The process number of this shell.
The process number of the last background
command invoked.
Special variables set by the shell
Examples:
$ echo $$
7828
$ echo $!
$ echo $?
0
$ echo $ims
$ echo $#
0
The shell variables used by the shell
HOME
The default argument (home directory)
for the cd command.
PATH
The search path for commands.
CDPATH The search path for the cd command.
PS1
Primary prompt string, by default `$ '.
PS2
Secondary prompt string, by default `>'.
IFS
Internal field separators, normally
SPACE, TAB, and NEWLINE.
SHELL When the shell is invoked, it scans the
environment for this name.
Positional parameters
Positional parameters are used to refer the
arguments list.
$0
$1
$* or
$@
$#
the shell script name
the first argument
all the arguments, starting with$1, are
substituted (separated by SPACE
characters).
The number of arguments in decimal.
The read Command
Syntax:
read variable [variable...]
Examples:
#!/bin/sh
# Shell Program
#
echo enter a sentence
read A
echo $A
Return status
The shell variable ? holds the return status of the last
command executed.
zero - true or no error
non-zero - false or error
Examples:
$ ls
$ echo $?
0
$ cp
Usage:
cp f1 f20
cp [-r] f1 . . . fn d1
$ echo $?
1
$ echo $?
0
The test Command
Syntax:
test expression
or
[ expression ]
We can test three types of things:
1. Files
2. Integers
3. Strings
The test Command - File Tests
Syntax:
test -option filename
or
[ -option filename ]
File test Options:
r readable
w writable
x executable
d directory
f plain file
s size greater than 0
File Tests
Examples:
$ test -f new.jersey
$ echo $?
0
$ [ -d new.jersey ]
$ echo $?
1
The test Command - String Tests
Syntax:
test
test
test
test
string1 = string2
string1 != string2
-z s1
True if the length of string s1 is zero.
-n s1
True if the length of the string s1 is
non-zero.
test s1
True if s1 is not the null string.
or
[ string1 = string2 ]
[ string1 != string2 ]
[ -z s1 ]
[ -n s1 ]
The test Command - String Tests
Examples:
$ X=abc
$ [ "$X" = "abc" ]
$ echo $?
0
$ [ "$X" != "abc" ]
$ echo $?
1
The test Command - Numeric Tests
Syntax:
test number relation number
or
[ number relation number ]
Relations:
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not equal to
The test Command - Numeric Tests
Examples:
$ x=3
$ [ $x -lt 7 ]
$ echo $?
0
The test Command - Other Operators
-o
-a
!
\( \)
OR
AND
NOT
GROUPING*
Examples:
$ test a != b
$ test ! -d name
$ test -f name1 -o -f name2
$ test \( -f name1 -o -f name2 \) -a -d name3
* Note: the ( ) must be escaped with a backslash.