Shell Scripts

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40
At a glance
Powered by AI
The key takeaways are that shell scripts allow grouping of commands to be executed regularly and stored in a file, shell scripts run in interpretive mode rather than being compiled, and .sh is a common file extension used for shell scripts.

The main components of a shell script are storing commands in a file, using an interpreter line to specify the shell to use, using comments to document the script, and making the script executable to run it.

Shell scripts run slower than programs written in other languages because each statement is loaded into memory and interpreted when executed rather than being compiled to machine code like other languages.

Shell Scripts

• When groups of command have to be executed


regularly, they should be stored in a file, and
the file itself executed as a shell script or a shell
program by the user.
• A shell program runs in interpretive mode. It is
not complied with a separate executable file as
with a C program but each statement is loaded
into memory when it is to be executed.
• Hence shell scripts run slower than the
programs written in high-level language.
• .sh is used as an extension for shell scripts.
Example: script.sh
#! /bin/sh
# script.sh: Sample Shell Script
echo “Welcome to Shell Programming”
echo “Today’s date : `date`”
echo “This months calendar:”
cal `date “+%m 20%y”` #This month’s calendar.
echo “My Shell :$SHELL”
• The # character indicates the comments in the
shell script and all the characters that follow the #
symbol are ignored by the shell.
• However, this does not apply to the first line which
beings with #.
• This because, it is an interpreter line which always
begins with #! followed by the pathname of the
shell to be used for running the script.
• In the above example the first line indicates that
we are using a Bourne Shell.
• To run the script we need to first make it
executable. This is achieved by using the chmod
command as shown below:
$ chmod +x script.sh
Then invoke the script name as:
$ script.sh
Once this is done, we can see output.
 As stated above the child shell reads and
executes each statement in interpretive mode. -
 We can also explicitly spawn a child of your
choice with the script name as argument:
sh script.sh
Note: Here the script neither requires a
executable permission nor an interpreter line.
Read: Making scripts interactive
• The read statement is the shell’s internal tool for
making scripts interactive (i.e. taking input from
the user). It is used with one or more variables.
• Inputs supplied with the standard input are read
into these variables. For instance, the use of
statement like
read name
causes the script to pause at that point to take
input from the keyboard. Whatever is entered by
you will be stored in the variable name.
Example: A shell script that uses read to take a search
string and filename from the
terminal.
#!/bin/sh
# emp1.sh: Interactive version, uses read to accept two inputs
#
echo “Enter the pattern to be searched: ”
read pname
echo “Enter the file to be used: ”
read fname
echo “Searching for pattern $pname from the file $fname”
grep $pname $fname
echo “Selected records shown above”
• Running of the above script by specifying the
inputs when the script pauses twice:
$ emp1.sh
Enter the pattern to be searched : director
Enter the file to be used: emp.lst
Searching for pattern director from the file
emp.lst
9876 Jai Sharma Director Productions
2356 Rohit Director Sales
Selected records shown above
Using Command Line Arguments
• Shell scripts also accept arguments from the
command line. Therefore they can be run non
interactively and be used with redirection and
pipelines.
• The arguments are assigned to special shell
variables. Represented by $1, $2, etc; similar
to C command arguments argv[0], argv[1], etc.
The following table lists the different
shell parameters.
Shell parameter Significance
• $1, $2… Positional parameters representing
command line arguments
• $# No. 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 separate
argument
• $? Exit status of last command
• $$ Pid of the current shell
• $! PID of the last background job.
Example: emp2.sh
#!/bin/sh
#emp2.sh: Non-interactive version - uses command line arguments

echo "program: $0"


echo "The number of arguments specified is $#"
echo "The arguments are $@"
grep "$1" $2
echo "Job Done"
exit and Exit Status of Command
• To terminate a program exit is used. Nonzero value indicates an
error condition.
Example 1:
$ cat foo
Cat: can’t open foo
• Returns nonzero exit status. The shell variable $? Stores this status.
Example 2:
grep director emp.lst > /dev/null;echo $?
0
• Exit status is used to devise program logic that braches into
different paths depending on success or failure of a command
Example: emp3.sh
#!/bin/sh
#emp3.sh: Non-interactive version - uses command line arguments with exit
status

echo "program: $0"


echo "The number of arguments specified is $#"
echo "The arguments are $@"
grep "$1" $2 >/dev/null;echo $?
echo "Job Done"
The logical Operators && and ||
• The shell provides two operators that allows
conditional execution, the && and ||.
• Usage:
cmd1 && cmd2
cmd1 || cmd2
• && delimits two commands. cmd2 executed only
when cmd1 succeeds(true)
• The || operator plays the reverse role. The
second command is executed only when the first
fails.
Example: emp4.sh
#!/bin/sh
#emp3.sh: Non-interactive version - uses
#command line arguments and exit status
echo "program: $0”
echo "The number of arguments specified is $#"
echo "The arguments are $@"
grep "$1" $2 && echo "pattern found"
echo "Job Done"
Example: emp5.sh
#!/bin/sh
#emp3.sh: Non-interactive version - uses
command #line arguments and exit status
echo "program: $0”
echo "The number of arguments specified is $#"
echo "The arguments are $@"
grep "$1" $2 || echo "pattern not found"
echo "Job Done"
The if Conditional
Form 1
Form2
if command is successful
if command is successful Form 3
Then
Then if command is successful
Execute commands
execute commands execute then
Fi
Else execute commands
execute commands elif command is successful
Fi execute commands then...
else...
fi
Example: emp6.sh
#! /bin/sh
if grep “^$1” emp1.sh 2>/dev/null
then
echo “Pattern Found”
else
echo “Pattern Not Found”
fi
Using test and [ ] to Evaluate
Expressions
• Test works in three ways:
Compare two numbers
 Compares two strings or a single one for a
null value
Checks files attributes
• Test doesn’t display any output but simply
returns a value that sets the parameters $?
Numeric Comparison
Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal
• Operators always begin with a – (Hyphen) followed by
a two word character word and enclosed on either side
by whitespace.
• Numeric comparison in the shell is confined to integer
values only, decimal values are simply truncated.
Ex:
$x=5;y=7;z=7.2
1. $test $x –eq $y; echo $?
1 //Not equal
2. $test $x –lt $y; echo $?
0 //True
3. $test $z –gt $y; echo $?
bash: test: 7.2: integer expression expected
2
4. $test $z –eq $y ; echo $y
bash: test: 7.2: integer expression expected
2
Example: emp7.sh
#!/bin/sh
#emp.sh: using test, $0 and $# in an if-elif-else-fi
#construct

if test $# -eq 0 ; then


echo "Usage : $0 pattern file" > /dev/tty
elif test $# -eq 2 ; then
grep "$1" $2 || echo "$1 not found in $2">/dev/tty
else
echo "You didn’t enter two arguments" >/dev/tty
fi
Shorthand for test
• [ and ] can be used instead of test. The following two forms are
equivalent
Test $x –eq $y
and
[ $x –eq $y ]
• String Comparison
• Test command is also used for testing strings. Test can be used to
compare strings with
• the following set of comparison operators as listed below.
• 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 a null string
stg String stg is assigned and not null
s1= =s2 String s1=s2
Example: emp8.sh
#!/bin/sh
#emp1.sh checks user input for null values finally prints the pattern matching lines
#
if [ $# -eq 0 ] ; then
echo "Enter the string to be searched :"
read pname
if [ -z "$pname" ] ; then
echo "You have not entered the string"; exit 1
fi
echo "Enter the filename to be used :"
read flname
if [ ! -n "$flname" ] ; then
echo " You have not entered the flname" ; exit 2
fi
grep "$pname" "$flname"
else
echo $*
fi
File Tests
• Test can be used to test various file attributes like its type (file, directory or
symbolic links) or its permission (read, write. Execute, UID, etc).
• The following table depicts file-related Tests with test:
Test True if
-f file File exists and is a regular file
-r file File exists and readable
-w file File exists and is writable
-x file File exists and is executable
-d file File exists and is a directory
-s file File exists and has a size greater than zero
-e file File exists (Korn & Bash Only)
-u file File exists and has SUID bit set
-k file File exists and has sticky bit set
-L file File exists and is a symbolic link (Korn & Bash Only)
f1 –nt f2 File f1 is newer than f2 (Korn & Bash Only)
f1 –ot f2 File f1 is older than f2 (Korn & Bash Only)
f1 –ef f2 File f1 is linked to f2 (Korn & Bash Only)
Example: emp9.sh
#!/bin/sh
#
if [ ! -e $1 ] ; then
echo "File doesnot exist"
elif [ ! -r $1 ]; then
echo "File not readable"
elif [ ! -w $1 ]; then
echo "File not writable"
else
echo "File is both readable and writable"
fi
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.
• Case also handles string tests, but in a more efficient
manner.
Syntax:
case expression in
Pattern1) commands1 ;;
Pattern2) commands2 ;;
Pattern3) commands3 ;;

Esac
Example: emp10.sh
#!/bin/sh
echo "
Menu
1. List of files 2. Processes of user 3. Today’s Date
4. Users of system 5.Quit"
echo "Enter your option:"
read choice
case "$choice" in
1) ls -l;;
2) ps -f;;
3) date;;
4) who;;
5) exit;;
*) echo "Invalid option"
esac
Matching Multiple Patterns:
Example: emp11.sh
case can also specify the same action for more than one
pattern . For instance to test a user response for both y and
Y (or n and N).

Example:
echo "Do you wish List the files in the current directory?
[y/n]:"
read ans
case "$ans" in
Y | y ) ls;;
N | n) exit;;
esac
Wild-Cards: case uses them:
Example : emp12.sh and emp13.sh
• Case has string matching feature that uses wild-cards. It
uses the filename matching metacharacters *, ? and
character class.
Example:
echo "Do you wish to list the file[yes/no]"
read ans
case "$ans" in
[Yy][eE]*) ls;; # Matches YE, ye, Ye, yE, YEs, yeS, YEskdk etc
[Nn][oO]) exit;; #Matches no, NO, No, nO
*) echo “Invalid Response”
esac
Example: emp13.sh
echo "Do you wish to list the file[yes/no]"
read ans
case "$ans" in
[Yy][eE]?) ls;; # Matches YES, yes, Yes, yEs, etc
[Nn][oO]) exit;; #Matches no, NO, No, nO
*) echo “Invalid Response”
esac
expr: Computation and String
Handling
• The Broune shell uses expr command to perform computations.
This command combines the following two functions:
 Performs arithmetic operations on integers
 Manipulates strings
• Computation:
• expr can perform the four basic arithmetic operations (+, -, *, /), as
well as modulus (%) functions.
Examples:
$ x=3 y=5
$ expr 3+5
8
$ expr $x-$y
-2
$ expr 3 \* 5 Note:\ is used to prevent the shell from
interpreting * as metacharacter
15

$ expr $y / $x
1

$ expr 13 % 5
3
expr is also used with command substitution to assign a variable.
Example1:
$ x=6 ;y=2 ; z=`expr $x + $y`
$ echo $z
8
Example2:
$ x=5
$ x=`expr $x+1`
$ echo $x
6
String Handling:
• expr is also used to handle strings. For
manipulating strings, expr uses two expressions
separated by a colon (:). The string to be worked
upon is enclosed on the left of the colon and a
regular expression is placed on its right.
• Depending on the composition of the
expression expr can perform the following three
functions:
1. Determine the length of the string.
2. Extract the substring.
3. Locate the position of a character in a string.
Length of the string:
• The regular expression .* is used to print the number of
characters matching the pattern .
Example1:
$ expr “abcdefg” : ‘.*’
7
• Example2: emp14.sh
while echo "enter your name: "; do
read name
if [ `expr "$name" : '.*'` -gt 5 ]; then
echo "Name is very long"
else
break
fi
done
• 2. Extracting a substring:
• expr can extract a string enclosed by the escape characters \
(and \).
Example:
$ st=2007
$ expr “$st” : ’..\(..\)’ #first two .. Ignore first two next two
prints last two charaters
07 Extracts last two characters.

• 3. Locating position of a character:


expr can return the location of the first occurrence of a
character inside a string.
Example:
$ stg = abcdefgh ; expr “$stg” : ‘[^d]*d’
4 Extracts the position of character d
Example: emp15.sh
• Shell script to read 5 digit number from print
last 3 characters of it.
while echo "enter 5 digit number: "; do
read num
echo "last three digits= `expr "$num" : '..\(...\)'`"
done
Example: emp16.sh
• Shell script to reads a string and print the
position of the specified character.

echo "enter your name: "


read name
while echo "Enter the character to display position"; do
read char
echo "position of character $char= `expr "$name" : '[^'$char']*'$char`"
done
While: Looping
• To carry out a set of instruction repeatedly shell
offers three features namely while, until and for.
Synatx:
while condition is true
do
Commands
done
• The commands enclosed by do and done are
executed repadetedly as long as condition is true.
Example: emp17.sh
#!/bin/usr
ans=y
while [ "$ans" = 'y' ]
do
echo "Enter the code and description :"
read code description
echo "$code $description" >> newlist
echo "Enter any more [Y/N]"
read any
case $any in
Y* | y* ) ans=y;;
N* | n*) ans=n;;
*) ans=y;;
esac
done

You might also like