Академический Документы
Профессиональный Документы
Культура Документы
A shell is a program that reads commands and executes them. Another name for a
shell is a command interpreter.
Current Unix shells, such as bash, ksh, and tcsh, provide numerous conveniences
and features for both interactive and programmatic purposes and are complicated
programs in their own right.
There are as many as 30+ Unix shells, but the most popular are sh, ksh, bash, csh
and tcsh.
When you manually type commands to the shell, you are running an interactive
shell. The shell features beneficial for interactive use are different from those needed
when running a script, in which the shell reads commands from a file.
In interactive use, shell features that minimize typing and tedium are important. For
scripting or programmatic use, flexibility, power and expressiveness are more
important.
In order to execute a file containing a shell commands the file should have the
execute permission.
sh myshellscript
./myshellscript
Note: If you are executing a script using sh then you need not to give execute
permission to shell script.
To execute the script inside the current shell (without forking) useful to load
environment variables in the current shell do:
. myshellscript
You may optionally specify the pathname of your shell interpreter in this case the
very first line of the shell script must contain a pound sign (#) in the first column
and an exclamation point in the second (!) followed by the pathname of the sh
executable.
#!/bin/sh
This notation is used by the system to determine which command interpreter should
be used to execute the file content.
Reading input
Reading from the terminal can be accomplish with the following syntax:
read myinput
Example:
When we put any command in back quotes like`command` (we use back quotes not
the normal forward quotes), then it is replaced by the output of the command.
Typically command only produces one line of output. For example the basename
PATH command strips off any directory portion of path, so to get the file name in a
script you usually see:
fff=/usr/share/timezone/Pacific.tz
filepart=`basename $fff` # filepart=Pacific.tz
Numeric variables
Operator Description
% Remainder of division
/ Divide
\* Multiply
+ Add
- Subtract
Operator Description
= Integer comparison (equal).
\> Integer comparison (greather).
\>= Integer comparison (greather or equal).
\< Integer comparison (less than).
\<= Integer comparison (less than or equal).
!= Integer comparison (not equal).
Operator Description
exp1 \| exp2 If exp1 is null or 0 return exp2 else return exp1.
If exp1 or exp2 are both not null or not zero return exp1 else return
exp1 \& exp2
0.
Compares exp1 with exp2 which is a regular expression returns the
exp1 : exp2 number of characters matched. The symbols \( \) can be used to
obtain a portion of exp1.
Operator Description
Returns the position in the first string of the first match
index str1 str2
found corresponding to the second string.
length string Returns the length of string.
Returns the substring of str that starts at start and has
substr str start length
length characters long.
Note: using expr you can carry mathematical operations on integer only.
Examples:
$ expr 7 + 5
12
$ i=`expr 3 \* 4 + 2`
$ echo $i
14
$ echo "result = `expr \( $i - 2 \) / 2`"
result = 6
These are some variables that have special meanings for the shell
Variable Description
$# Number of arguments.
$* All arguments.
$@ All arguments enclosed in quotes.
$0 Name of the script.
$1 First argument.
$n Replace n by a number between 0 and N to obtain the corresponding
argument.
$! Process id of the last process started in background.
Operator Description
command1 && command2 Causes command2 to be executed only if command1
returns a 0 (zero) exit value.
command1 || command2 Causes command2 to be executed only if command1
returns a nonzero exit value.
Variable Description
$cwd Current working directory.
$shell Pathname of the shell.
$HOME The user login directory.
$? Exit status of the last command 0 (zero) means OK.
$$ Process Id of the current shell.
$- Execution flags.
To check the exit code of the most recent command you executed, use the variable
$?. For example:
Here you execute a grep command and then check the exit status of this command
using the value stored in $?.
Conditional Execution
Two simple forms of conditional execution are available through the commands &&
and || their meanings are the following:
A zero exit value means that the program exited without errors, a nonzero exit value
means that the program exited with an error the return value identifies the error
code.
Examples:
Control structures
In order to control the flow of execution the shell supports the following flow control
structures.
if - The format of the if flow control structure is as follows:
I)
if test-command ; then
command
fi
II)
if test-command ; then
commands
elif test-command ; then
commands
.
.
else
commands
fi
III)
if test-command
then
commands
else
commands
fi
IV)
if test-command
then
commands
fi
Examples:
#
if test "$1" = "XX" ; then
echo "The first argument is XX"
fi
#
if [ ! -e $HOME/prog.f ] ; then
echo "File does NOT exist"
elif [ -d $HOME/prog.f ] ; then
echo "File is a directory"
elif [ -f $HOME/prog.f ] ; then
echo "File is a plain normal file"
fi
Example:
#
trap abort 1 2 3 4
while true ; do
echo "Program running..."
done
until test-command
do
commands
done
Example:
#
count=0
max=10
until [ $count -gt $max ] ; do
count=`expr $count + 1`
echo "Program running..."
done
while test-command
do
commands
done
Example:
#
count=0
max=10
while [ $count -le $max ] ; do
count=`expr $count + 1`
echo "Program running..."
done
The statement for performs a loop executing the commands block for
each one of the specified items. In each loop the iterator variable
assumes the value of one item following the specified order. The for
statement can be interrupted with a break or continue statements.
Break terminates the loop and resumes execution on the statement
after the end statement. Continue transfers control to the end
statement which will continue the loop.
Example:
#
for file in *.a
do
echo $file
nm $file | grep gamma
done
case string in
pattern1)
commands
;;
pattern2)
commands
;;
.
.
*)
commands
;;
esac
Example:
#
echo "Answer YES or NO: "
read answer
case "$answer" in
YES)
echo "Answer is YES"
;;
NO)
echo "Answer is NO"
;;
*)
echo "Answer is neither YES or NO"
;;
esac
Functions
A shell function is similar to a shell script since they both store commands, however
a shell function is stored in memory once is loaded from a script. Functions can be
remove from memory with the unset command. The general syntax for a function
is:
function-name ( )
{
commands
.
.
}
Example:
#
findarchive()
{
for file in $1/*.a ; do
nm $file | egrep "^$1|$2"
done
}
The function findarchive accepts two arguments, the name of a directory where
archive files (.a) are kept and the name of a routine to search for in all archive files.
The for loop is used to loop through all the archives in the directory. The nm
command lists all the archived symbols (routines, functions etc.). The command
egrep displays all the lines containing the symbol we are searching for and also lines
beginning with the directory name (the complete pathname of each archive).
Include functions and variable definitions from one file into another file
To include functions and variable definitions defined in one file into another file you
need to use the . command as follows:
. filexit
I/O Redirection
Redirection of I/O refers to the multiple ways the Bourne shell can be instructed to
alter where a command gets its input and where it sends its output to. By default the
shell associates the input and output of a command to the login terminal. Users can
change this default behaviour instructing the shell to redirect the input or output to
other device, a file or a command.
Each UNIX process is created with three files already open, they are:
Descriptor Descriptor
Name Meaning
Name Number
Standard Input (stdin) 0 The process input.
Standard
(stdout) 1 The process output.
Output
Where to write error
Standard Error (stderr) 2
messages.
To redirect the standard output to a file use the symbol > after the command and its
arguments. The general syntax is:
Example:
To redirect the standard error to a file so that error messages use the notation 2> .
The general syntax is:
Example:
The above syntax means redirect descritor number 2 (standard error) to a file, in
fact in the place of the number two you can use numbers between 1 and 9 to
redirect any of the first file descriptors, remember 0 is the standard input you can
not redirect descriptor 0 for output unless you close it first with the command <&- .
Standard output can also be closed with the command >&- .
To redirect the standard output and standard error to the same file so that error
messages and output can be found together use the following notation.
Example:
The above sintax means to redirect standard output to a file and associate the
descriptor number 2 (standard error) to descriptor number 1 (standard output).
To redirect and append the standard output and standard error to the same file so
that error messages and output can be found together use the following notation.
Example:
To redirect the standard input to a file in order to force a command to read its input
from a file use the notation < . The general syntax is:
To use the current standard input file as input until a string marker is found on a line
use the notation << . The general syntax is:
command <<marker
Example:
Note that between the redirection indicator (<<) and the marker string there are no
white spaces.
The shell stdin, stdout and stderr can be redirected to any file through the exec
command.
Example:
Example:
Example:
To restore the shell descriptors back to your terminal use the syntax:
Example:
The output of a command can also be redirected to other command. The shell uses a
pipe to connect the standard output of a command to the standard input of another
command. A pipe has the same final effect as redirecting the output of the first
command to a file and then redirect the standard input of the next command to read
from the same file. The pipe symbol is the vertical bar | . The general syntax is:
To redirect the standard output to other command use the symbol | after the
command and its arguments. The general syntax is:
Example:
aflip01> ls -l | more
aflip01> find /cern/pro/lib -name '*.a' -exec nm {} \; | grep gamma |
more
aflip01> man csh | a2ps | lpr -Plps
To redirect the standard output and standard error to other command use the
following syntax:
Example:
Here command is the name of the command you want to execute. The file is a
special file (called the bit bucket) that automatically discards all its input.
Example
ls –l > /dev/null
This will send out put of ls command to /dev/null and on screen you will not get
anything.
To discard both output of a command and its error output, use standard redirection
to redirect STDERR to STDOUT
Debugging Scripts
Built-in commands are part of (built into) the shell. Built-in commands are executed
internally without a fork by the shell. If a UNIX command has the same name of an
internal command the internal command will be executed instead.
Command Description
: Null command.
. Execute a shell script as part of the current process (without fork).
`pgm` Execute pgm and replace the text between ` ` by the command output.
break Exit from a FOR, UNTIL or WHILE loop.
bg Move a command to background (zsh, bash, ksh).
cd Change working directory.
continue Jump to the next loop iteration valid for WHILE, UNTIL and FOR loops.
echo Display the arguments.
eval Scan and evaluate the command line.
exec Load a new program into the current process, the current shell is lost.
exit Exit from current shell.
export Place a variable in the environment in order to be used by subprocesses.
fg Move a command to foreground (zsh, bash, ksh).
getopts Parse the shell script arguments.
hash Remember the location of a command in the search path.
jobs List current jobs (zsh, bash, ksh).
pwd Print the pathname of the current directory.
read Read a line from the standard input.
readonly Declare a variable to be readonly.
return Exit from a function.
set Changes the shell flags or command line arguments, without arguments
displays the list of variables.
shift Shift left the line arguments.
stop Stop a background job (zsh, bash, ksh).
test Make comparisons.
times Display times for the current shell and its children.
trap Intercept a signal.
type Display how each argument would be interpreted as a command.
shift Increments the index of the argv array hence shifting the command
arguments by one.
ulimit Limit the size of files written by the shell.
umask Displays and changes the mask for default access permissions.
unset Removes a variable declared with the set command.
wait Causes the C shell to wait until all background processes finish.