Sie sind auf Seite 1von 25

Unix Shell Scripting

Slide 1
Contents

 Introduction to Shell scripting


 Shell Scripts
 read Making scripts interactive
 Using COMMAND LINE ARGUMENTS
 exit AND EXIT STATUS OF COMMAND
 Logical Operators && AND ||
 The if CONDITIONAL
 USING test AND [] TO EVALUATE EXPRESSIONS
 String Comparison
 File Tests
 THE case CONDITIONAL

Slide 2
Contents

 Matching Multiple patterns


 expr Computation and String handling
 String HANDLING
 Locating Position of a character
 While Looping
 Using While to wait for a File
 for looping with a list
 set Manipulating the positional parameters
 Shift shifting arguments left
 The Here document (<<)
 Trap Interrupting a program
 Debugging shell script with set –x
 Sample validation and Data entry scripts

Slide 3
Introduction to Shell scripting

1.UNIX shell scripts are text files that contain sequences of UNIX commands
2.It has variables, conditionals and loops
3.Like high-level source files, a programmer creates shell scripts with a text
editor or vi Editor
4.Shell scripts do not have to be converted into machine language by a compiler
5.This is because the UNIX shell acts as an interpreter when reading script files
6.As an interpreter reads the statements in a program file, it immediately
translates them into executable instructions, and causes them to run
7.After you create a shell script, you simply tell the operating system that the file
is a program that can be executed

Slide 4
Shell Scripts

When a group of commands have to be executed regularly, they should be stored


in a file and the file itself executed as a shell script or shell program

we use .sh extension for shell scripts

Ex :sample.sh

#!/bin/sh
#script.sh: Sample shell script
echo "Today's date is: `date` "
echo "This month calendar:"
cal `date "+%m 20%y"`
echo "My shell: $SHELL"

Use vi editor or simple text files to create shell scripts


#!  followed by path name of the shell to be used for running scripts
# comment character which can be placed anywhere in the script ignores
characters placed on right

Note: to run the script make it executable first


chmod 777 filename.sh

Slide 5
read Making scripts interactive
 read statement is the shell's internal tool for taking input from the user i.e..,
making scripts interactive
 Its is used with one or more variables
 Input supplied through the standard input is read into these variables
#!/bin/sh
#emp1.sh: Interactive vesrsion - uses read to take
# two inputs

echo "Enter the pattern to be searched: \c"


read pname
echo "Enter the file to be used: \c"
read flname
echo "searching for $pname from file $flname"
grep "$pname" $flname
echo "Selected records shown above"

Slide 6
Using COMMAND LINE ARGUMENTS
Shell scripts accepts arguments from the command line
when arguments are specified with a shell scripts, they are assigned to
certain special variables rather positional parameters
Special Parameters used by the shell
Ex:emp2.sh

Shell Significance
Parameter
$1,$2...... Positional parameters representing command line
arguments
$# Number of arguments specified in command line
$0 Name of the executed command
$* Complete set of positional parameters as a single string
"$@" Each quoted string treated as a separate argument
$? Exit status of the last command
$$ PID of the current shell
$! PID of the last background job

Slide 7
exit AND EXIT STATUS OF COMMAND
Used to terminate a program
exit status is extremely important for programmers to branch into different paths

common exit values


exit 0 Used when everything went fine
exit 1 Used when something went wrong

•You don't need to place this statement at the end of every script
•Its through the exit command or function that every command return an
exit status
•Command is said to return a true exit status if it executes successfully and false
if it fails
ex: cat foo
cat: can't open foo
->returns a nonzero exit status because it could not open the file
Shell offers a variable ($?) and a command (test) that evaluates a command's exit status
Parameter $? stores the exit status of the last command
Ex:
grep director emplist.lst >/dev/null; echo $?
0
grep salws emplist.lst >/dev/null; echo $?
1
grep salws emplist3.lst > /dev/null; echo $?
grep: can't open emplist3.lst
2
Slide 8
Logical Operators && AND ||
Used to provide conditional execution
syntax:
cmd1 && cmd2
cmd1 || cmd2

cmd1 && cmd2: executes two commands and the cmd2 is executed only when
cmd1 is successful
ex: grep 'director' emplist.lst && echo "pattern found in file"

cmd1 || cmd2: executes two commands and the cmd2 is executed only cmd1
fails
ex: grep 'Admin' emplist.lst || echo "Pattern not found"

Slide 9
The if CONDITIONAL
FORM 1 Ex:emp3.sh
if command is #!/bin/csh
successful #checks department exists or not
then # emp3.sh
execute commands echo "enter a department:"
fi read department
FORM2 if grep "$department" emplist.lst
if command is then
successful
echo "Department found"
then
execute commands
else
else echo "Department not found"
execute commands fi
fi
FORM3
if command is
successful
then
execute commands
elif command is
successful
then ....
else ......
fi

Slide 10
USING test AND [] to evaluate Expressions
When you use if to evaluate expressions you required the test statement because
the true or false values returned by expressions can't be directly handled by if
test works in 3 ways:
compare 2 numbers
compares 2 strings
checks files attributes
Numeric comparison operators used by test
They always begin with - (hyphen) followed by a two character word
syntax

-ne not equal


-lt less than
-gt greater than
-eq equal
-ge greater than or equal to
-le less than or equal to

Ex:emp3a.sh
#!/bin/sh
#emp3a.sh
x=5; y=7; z=7.2
test $x -eq $y ; echo $?
test $x -lt $y ; echo $?
test $z -gt $y ; echo $?
test $z -eq $y ; echo $?
Slide 11
String Comparison

Test can be used to compare strings with another set of operators


Ex: emp4.sh

Test TRUE IF
s1 = s2 String s1= s2
s1!= s2 String s1 is not equal to s2
-n stg String stg is not a null string
-z stg String stg is assigned and not null
s1 == s2 String s1 = s2 (Korn and Bash only)

Slide 12
File Tests

Test can be used to test the various file attributes like its type (file, directory
or symbolic link) or its permissions (read, write, execute, SUID, etc )
Ex: filetest.sh

File-related Tests with test


-f file file exists and is regular file
-r file file exists and is readable
-w file file exists and is writable
-x file file exists and is executable
-d file file exists and is directory
-s file file exists and has a size greater than zero

-e file file exists


-u file file exists and has SUID bit set
-k file file exists and has a sticky bit set
-L file file exists and is a symbolic link
f1 -nt f2 f1 is newer than f2
f1 -ot f2 f1 is older than f2
f1 -et f2 f1 is linked to f2

Slide 13
THE case CONDITIONAL
 The case statement is the second conditional offered by the shell
 The statement matches an expression for more than one alternative, and uses
a compact construct to permit multi way branching\

syntax
case expression in
pattern1) ;;
pattern2) ;;
pattern3) ;;
.......
Esac
Ex: Menu.sh
#!/bin/sh
# menu.shL Uses case to offer 5- item menu
echo " Menu\n
1. list of files\n2. Processes of user\n3. today's Date
4. Users of System\n5. Quit to UNIX\nEnter your option: \c"
read choice
case "$choice" in
1) ls -f ;;
2) ps -f ;;
3) date ;;
4) who ;;
5) exit ;;
*) echo "Invalid option" # ;; not really happened required for the last
option
esac

Slide 14
Matching Multiple patterns

 Case can also specify the same action for more than one pattern.
 Programmers frequently encounter a logic that has to test user response for
both y and n
 Like grep -E and grep
 Case uses the \ to delimit multiple patterns
Ex: Menu1.sh
#!/bin/sh
#menu1.sh
echo "Do you wish to continue? (y/n): \c"
read answer
case "$answer" in
y/Y) ;;
n/N) exit ;;
esac

Slide 15
expr Computation and String handling

 Can be used to perform arithmetic operations on integers Manipulates strings


 expr can perform the four basic arithmetic operations, as well as the modulus
(remainder) function

ex: Compu.sh
#!/bin/sh
#compu.sh: sample computation shell script
a=5 b=6
echo `expr $a + $b`
echo `expr $a - $b`
echo `expr $a / $b`
echo `expr $a \* $b`
echo `expr $a % $b`
echo `expr $a + 1`
NOTE: operand +,-,* etc., must be enclosed by white space on either side.
multiplication operand(*) must be escaped to prevent the shell interpreting it
as the file name

Slide 16
String HANDLING
 For manipulating strings, expr uses two expressions separated by a colon
 The string to be worked upon is placed on left of the regular expression is
placed on right hand side.
 Is used to determine the length of a string, extract a substring and locate
the character in string.

Note: Here, expr is used to count the characters i,e.. (.*)

ex: length.sh

#!/bin/sh
#length.sh: to check if length of character > 20
while echo "Enter your name: \c" ; do
read name
if [ `expr "$name" : '.*'` -gt 20 ] ; then
echo "name too long"
else
break
fi
done

Slide 17
String HANDLING cont..

Extracting a Substring: expr can extract a string enclosed by the escaped characters
\ (and \)

ex: substring.sh

#!/bin/sh
#script.sh: Sample substring script
echo "enter 4 character string"
read character
echo `expr "$character" : '..\(..\)'`

Above sample signifies that the first two characters has to be ignored and
two characters has to be extracted from the third character position

i.e. (\1 and \2 here).

Slide 18
Locating Position of a character

 expr is used to return the location of first occurrence of a character inside a


string.
 [^d]*d is used to count the characters which are not d

Ex: postion.sh

#!/bin/sh
# position.sh: Sample character position script
echo "enter string containing D to find position of D"
read character
echo `expr "$character" : '[^d]*d'`

Slide 19
While Looping
Loops let you perform a set of instructions repeatedly.
Shell features 3 types of loops: while, until, and for
All of them repeat the instruction set enclosed by certain keywords
as often as their control command permits.
While loop performs set of instructions till the controls command
retunes a true exit status

While loop syntax:


While condition is true
do
Commands…..
Done

Slide 20
While Looping cont…
Ex: emp5.sh
#!/bin/sh
#emp5.sh: Shows use of the while loop
#
answer=y # must set it to y first to enter
the loop
while [ "$answer" = "y" ] # the control command
do
echo "Enter the code and description: \c" >/dev/tty
read code description # read both together
echo "$code|$description" >>newlist # Append a line to
newlist
echo "Enter any more (y/n)? \c" >/dev/tty # read both
together
read anymore
case $anymore in
y*|Y*) answer=y ;; #Also accepts yes, YES etc.
n*|N*) answer=n ;; #Also accepts no, NO etc.
*) answer=y ;; #Any other reply means y
esac
done

Slide 21
Using While to wait for a File
 There are situations when a program needs to read a file that is created by
another program
 The below sample script periodically monitors the disk for the existence of the file
and then executes the program once the file has been located.
 It makes use of external command sleep that ,makes the script pause for the
direction (in seconds) as specified in arguments

Ex: monitfile.sh
#!/bin/sh
# monitfile.sh: waits for a file to be created
#
while [!–r invoice.lst] #while the file invoice.lst can’t be read

do
sleep # sleep for 60 seconds

done
Alloc.pl #execute this program after executing the while loop
Note: (! – r )means not readable
Sleep command is used to check the existence of the file

Slide 22
for looping with a list

 The shell for loop differs in structure from the ones used in other
programming language.
 Unlike while and until, for doesn’t test a condition, but uses a list instead
Syntax:
for variable in list
do
commands….
done
Ex:emp6.sh
# !/bin/sh
# emp6.sh: using a for loop with a positional parameters
#
for pattern in "$@" ; do
grep "$pattern" emplist.lst || echo "Pattern $pattern not found"
done
Note: run this command as sh emp6.sh 2345 1265 4379

Slide 23
set Manipulating the positional parameters
 Some UNIX commands like date produce single-line output through filters
like grep and head to produce a single line.
 So we need cut command to extract a field from the output
 But this is overkill to UNIX, the shell has a internal command to do this
job– the set command
 It assigns the positional parameters like $1, $2, and so on, to its arguments.
 This is useful for picking up individual fields from the output of a program

Ex: set.sh
# !/bin/sh
# set.sh: used to convert arguments to positional parameters
set `date`
echo $*
$echo "The date today is $2, $3,$4"

Slide 24
Shift shifting arguments left
 Shift transfers the contents of a positional parameters to its immediate lowered
numbered on
 This is done as many times as the statement called
 When called once, $2 becomes $1, $3 becomes $1, and so on.

 Ex: emp7.sh
# !/bin/sh
# emp7.sh:script using shift --Saves first argument;
#
case $# in
0|1) echo "Usage: $0 file pattern(s)"; exit 2 ;;
*) flname=$1 # Store $1 as variable before it gets lost shift
for pattern in "$@" ; do # starts iteration with $2
grep "$pattern" $flname || echo "Pattern $pattern not found"
done ;;
esac
Note:
 every time you use shift, the leftmost variable gets lost; so it should be saved
in a variable before using shift.
 If you have to start iteration from the fourth parameter, save the three
parameters and then use shift 3

Slide 25

Das könnte Ihnen auch gefallen