Vous êtes sur la page 1sur 25

SHELL SCRIPTING

TIBCO Software Inc.

This document (including, without limitation, any product roadmap or statement of direction data) illustrates the planned testing, release and availability dates for TIBCO products and services. This document is provided for informational purposes only and its contents are subject to change
without notice. TIBCO makes no warranties, express or implied, in or relating to this document or any information in it, including, without limitation, that this document, or any information in it, is error-free or meets any conditions of merchantability or fitness for a particular purpose. This
document may not be reproduced or transmitted in any form or by any means without our prior written permission.

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
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

Introduction to Shell scripting


expr Computation and String handling
1.UNIX shell scripts are text files that contain sequences of UNIX commands
String
HANDLING
2.It has variables, conditionals and loops
Locating
Position of a character
3.Like high-level source files, a programmer creates shell scripts with a text
While
editorLooping
or vi Editor
Using
While
for atoFile
4.Shell
scriptstodowait
not have
be converted into machine language by a
for compiler
looping with a list
5.This
is because the
shell acts
as an interpreter when reading script files
set
Manipulating
theUNIX
positional
parameters
6.As
an interpreter
reads theleft
statements in a program file, it immediately
Shift
shifting
arguments
them into executable instructions, and causes them to run
Thetranslates
Here document
(<<)
7.After you create a shell script, you simply tell the operating system that the
Trap
a program
fileInterrupting
is a program that
can be executed
Debugging shell script with set x
Sample validation and Data entry scripts

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

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
read
echo
read
echo
grep
echo

"Enter the pattern to be searched: \c"


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

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

exit AND EXIT STATUS OF


COMMAND

Used to terminate a program


exit status is extremely important for programmers to branch into different paths

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

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'

found"

emplist.lst || echo "Pattern not

The if CONDITIONAL

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

String Comparison
Test can be used to compare strings with another set of operators
Ex: emp4.sh

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

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

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

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:
a=5 b=6
echo `expr
echo `expr
echo `expr
echo `expr
echo `expr
echo `expr

sample computation shell script


$a
$a
$a
$a
$a
$a

+ $b`
- $b`
/ $b`
\* $b`
% $b`
+ 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

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
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

on right hand side.

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).

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'`

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 Looping cont

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 cant 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

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 doesnt 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

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"

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

Vous aimerez peut-être aussi