Beruflich Dokumente
Kultur Dokumente
UNIT 16
bash Shell Scripting
Rev RH033-RHEL3-1
Rev RH033-RHEL3-1
Rev RH033-RHEL3-1
Scripting Basics
Shell scripts are text files that contain a
series of commands or statements to be
executed.
Shell scripts are useful for:
Automating commonly used commands
Performing system administration and
troubleshooting
Creating simple applications
Manipulation of text or files
Rev RH033-RHEL3-1
Rev RH033-RHEL3-1
Rev RH033-RHEL3-1
Generating Output
Use echo to generate simple output
echo 'Welcome to Red Hat Linux paradise!'
echo -n "Please enter the file name: "
Handling Input
Use read to assign an input value to a
shell variable:
echo -n "Enter the filename: "
read FILENAME
read reads from standard input and assigns
Rev RH033-RHEL3-1
1
1
Exit Status
Commands exit with an exit status
0 for success, 1 to 255 for failure
Exit status of most recently executed
command is kept in the $? variable just
like return values from shell functions
Control Structures
The three types in shell programming :
Sequential structures - the program flows
one line after another
Selection structures - code execution based
on a logical decision
if, if/else , if/elif/else and
conditional operators
1
3
Conditional Execution
Commands may be executed
conditionally, based on the exit status of
the previous command
&&
||
logical AND
logical OR
Examples:
$ grep joe passwd || echo 'No joe!'
$ cp -a /tmp/*.o . && echo 'Done!'
1
4
Rev RH033-RHEL3-1
Selection Structures:
Using the if Statement
if selection structures execute the body
File Tests
File tests:
-f tests to see if file exists and is a
regular
file
-d tests to see if a file exists and is a
directory
-x tests to see if a file exists and is
executable
if [ -f $HOME/lib/functions ];then
source ~/lib/functions
1
6
fi
Rev RH033-RHEL3-1
String Tests
Strings may be tested as well
-z returns true if the string is empty
-n returns true if the string is not empty
1
7
Copyright 2003 Red Hat, Inc.
Selection Structures
Using if/else Statements
if/else selection structures execute
the body of the if structure only if the
1
8
Selection Structures:
Using the case Statement
The case statement provides an
alternative method for performing
selections that may be cleaner than
multiple if/elif/else tests
case variable in
pattern1)
do something ;;
pattern2)
do another thing ;;
esac
Rev RH033-RHEL3-1
1
9
Repetition Structures:
The for-loop
The for repetition structure provides a
method for iterating, or looping, through
a list of values and executing commands
on each of these values.
for variable in list- of- values
do
commands...
done
Rev RH033-RHEL3-1
2
0
Selection Structures
The while-loop
The while loop structure provides a
useful method for performing a set of
commands while a condition remains
true. The syntax is:
while condition
do
commands...
done
2
1
Rev RH033-RHEL3-1
2
2
End of Unit 16
Questions and answers
Summary
2
4
Rev RH033-RHEL3-1