Shell Script Programming

Download Report

Transcript Shell Script Programming

Shell Script Programming
Using UNIX Shell Scripts
Unlike high-level language programs, shell
scripts do not have to be converted into machine
language by a compiler
The UNIX shell acts as an interpreter when
reading script files
Interpreters read statements in script files and
immediately translate them into executable
instructions and cause them to run
2
Using UNIX Shell Scripts
After creating shell script, the OS is instructed
that the file is an executable shell script via the
chmod command
When the file is designated as executable, you
may run it in one of many ways:
– Type the script name at the command prompt after
updating the path variable
– If the script is in the current directory, proceed its
name at the prompt with a dot slash (./)
– If not in the current directory, specify the absolute
path at the command prompt
3
Ensuring the Correct Shell
Runs the Script
In Unix there is more than one shell !
– examples: bash, tcsh, ksh
need to ensure that correct shell runs the script
different shells use different programming
constructs
Convention: first line of a script states which
executable should run script
Example:
#! /bin/sh
4
Variables
Variables are symbolic names that represent
values stored in memory
Three types of variables are:
– Configuration variables store information about the
setup of the OS
– Environment variables hold information about your
login session
– Shell variables are created at the command prompt or
in shell scripts and are used to temporarily store
information
5
Variables
To set:
example=one
To see:
echo $example
To make part of the environment:
export example
To remove:
unsetenv example
6
Variables
Use the printenv command to see a list
of environment variables
7
Some Variables
HOME
home directory
USER
user name
PATH
list of command directories
PWD
current directory
8
Shell Operators
Bash shell operators are in three groups:
– Defining and Evaluating operators are used to set a
variable to a value and to check variable values
The equal sign (=) is an example
– Arithmetic operators are used to perform
mathematical equations
The plus sign (+) is an example
– Redirecting and piping operators are used to specify
input and output data specifications
The greater than sign (>) is an example
9
Shell Operators
10
Wildcard Characters
Shell scripts often use wildcard characters
Wildcard characters are intended to match
filenames and words
– Question mark (?) matches exactly one
character
– Asterisk (*) matches zero or more characters
– [chars] defines a class of characters, the glob
pattern matches any singles character in the
class
11
Shell Logic Structures
Four basic logic structures needed for
program development are:
– Sequential logic
– User input
– Decision logic
– Looping logic
– Case logic
12
Sequential Logic
commands are executed in the order in
which they appear in the script
break in sequence occurs when a branch
instruction changes the flow of execution
by redirecting to another location in the
script
13
User input
Script can read user data
Command: read variable
reads user input and assigns text to
variable
14
User input
Command: read var1 var2 var3
reads 3 words and assigns 3 variables
Last variable contains rest of input line
15
User input
Command:
read –p “enter name: “ name
Prompts user, then reads input and
assigns to variable
16
User input example
17
Decision Logic
Enables your script to execute statement(s)
only if a certain condition is true
Condition:
– result of a command
– Comparison of variables or values
if statement
18
If statement
Syntax:
if [ condition ]
then
statements
else
statements
fi
19
Decision Logic example
20
Nested Decision Logic
21
Looping Logic
A control structure repeats until some
condition exists or some action occurs
Two common looping mechanisms:
– For loops cycle through a range of values until
the last in a set of values is reached
– The while loop cycles as long as a particular
condition exists
22
For Loop
Syntax
for var in list
do
statements
done
23
For Loop example
Program
control
structures
can be
entered from
the
command
line
24
For loop in script
25
Loop with wildcard
26
While Loop
Syntax
while [ condition ]
do
statements
done
27
Looping Logic
The while
loop tests
repeatedly
for a
matching
condition
28
Looping Logic
While loops
can serve as
data-entry
forms
29
While loop to enter data
30
Case Logic
The case logic structure simplifies the
selection from a list of choices
It allows the script to perform one of many
actions, depending on the value of a
variable
Two semicolons (;;) terminate the actions
taken after the case matches what is being
tested
31
Case statement
Syntax:
case $variable in
“pattern1”)
statements
;;
“pattern2”)
statements
;;
esac
32
Case example
33
Case Logic
34
Debugging a Shell Script
Shell script will not execute if there is an error in
one or more commands
sh has options for debugging
– sh -v
displays lines of script as they are read by the
interpreter
– sh -x
displays the command and its arguments line by line
as they are run
35
Debugging a Shell Script
View the script
line by line as it is
running to help
locate errors
36
Using Shell Scripting to
Create a Menu
A menu is a good example of a shell script
that employs the four basic logic structures
A significant feature of the menu script is
the screen presentation which should be
as appealing and user-friendly as possible
37
tput command
tput clear
– clear the screen
tput cup r c
– position cursor to row and column
– ex: tput cup 0 0
tput cup 20 10
bold=`tput smso`
offbold=`tput rmso`
38
Example
tput clear; tput cup 10 15;
echo “Hello”; tput cup 20 0
39
Creating a Menu
tput can be
used to help
create data
entry screens
40
Creating a Menu
41
Creating a Menu
tput can be
used to help
create user
menus
42
Creating a Menu
43
The trap Command
used to guard against abnormal
termination of script
– user ^C
– OS intervention
normal: remove temporary file
example:
trap ’rm ~/tmp/*’ 2 15
44
The awk Command
Allows simple formatting of output
– Reads input line by line
– Line contains fields (need field separator)
– Use C printf command to format output
45
Example: corp_phones
awk -F ':' ‘{printf("%-12s %-10s %10s\n",$2,$3,$1)}’ corp_phones
46
Shell script: phoneadd
The phoneadd
script allows to
add new records
to the
corp_phones file
47
Shell script: phoneadd
48
Complete script: phmenu
49
Script parameters
Command line invocation may list
parameters
Example:
myscript one two three
Available inside scripts as $1, $2, $3
50
Parameter example
51
Script Parameters
52
More Script Parameters
53
Numeric variables
Let command defines integer variables
with numeric values
Example:
let i=1
let i=5*i-2
Let command allows simple numeric
calculations
54
Using the test Command
Bash shell uses test command to:
– perform relational tests with integers
– test and compare strings
– check if a file exists and what type of file it is
– perform Boolean tests
Test command is standard Unix command
Is used in bash for if and while statements
55
Using the test command
Syntax:
test some-expression
[ some-expression ]
Indicates result via exit status
– 0 is true, 1 is false
To get exit status:
echo $?
56
Relational Integer Tests
57
String Tests
58
Testing Files
59
Performing Boolean Tests
60
Using the test Command
61
Quoting
Double quotes
example: text=“hello world”
echo “here it is: $text”
Single quotes
example: text=‘one two three’
echo “here it is: $text”
Execution quote
example: text=`date`
echo “here it is: $text”
62
Review: sed
Can be used to remove lines from a file
Syntax:
sed ‘/pattern/d’ file1 > file2
Removes all lines which match the
pattern from file1
63
Deleting Phone Records
The menu has
been updated to
allow for deleting
a phone record
64
Deleting Phone Records
Examine the
corp_phones file
before deleting
a record
65
Deleting Phone Records
The sed
command is
behind the delete
option
66
Deleting Phone Records
The record is no
longer in the file
67
Shell functions
Used to group recurring code
Syntax:
functionname() {
commands
}
68
Shell function example
datenow() {
date
}
it=`datenow`
echo $it
69
Shell function parameters
checkfile() {
echo “Checking: $1”
if [ -f “$1” ]
then
echo “$1 is a file”
else
if [ -d “$1” ]
then
echo “$1 is a directory”
fi
fi
}
checkfile phmenu
70