0% found this document useful (0 votes)
78 views12 pages

Shell Scripts: Unit 4 Essential Shell Programming

(1) Shell scripts allow storing commands in a file to be executed regularly. They are run in a separate child shell process which can be of a different type than the login shell. (2) To run a shell script, execution permission must be given using chmod and then running the script using ./scriptname or specifying the shell interpreter. (3) Common shell programming constructs include conditional statements like if/case, reading user input with read, testing files with test, and performing computations/string handling with expr.

Uploaded by

Shweta kumbhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views12 pages

Shell Scripts: Unit 4 Essential Shell Programming

(1) Shell scripts allow storing commands in a file to be executed regularly. They are run in a separate child shell process which can be of a different type than the login shell. (2) To run a shell script, execution permission must be given using chmod and then running the script using ./scriptname or specifying the shell interpreter. (3) Common shell programming constructs include conditional statements like if/case, reading user input with read, testing files with test, and performing computations/string handling with expr.

Uploaded by

Shweta kumbhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT 4 ESSENTIAL SHELL PROGRAMMING

SHELL SCRIPTS
When a group of commands have to be executed regularly ,they should be stored
in a file ,and the file itself executable as a shell script or shell program. Though it’s not mandatory
,we normally use the .sh extension for shell scripts , this makes it easy to match then with wild –
cards.

Shell scripts are executed in a separate child shell process ,and this sub-shell need not
be of the same type as your login shell. In other words ,even if your login shell is Bourne ,you can
use a Korn sub-shell to run your script. By default ,the child and parent shells belong to the same
type ,but you can provide a special interpreter line in the first line of the script to specify a different
shell your script.

Running a shell script


Because of security of files, in Linux, the creator of Shell Script does not get execution
permission by default. So if we wish to run shell script we have to do two things as follows
(1) Use chmod command as follows to give execution permission to our script
Syntax:
chmod +x shell-script-name
OR Syntax:
chmod 777 shell-script-name
(2) Run our script as
Syntax:
./your-shell-program-name
For e.g.
$ ./first
Here '.'(dot) is command, and used in conjunction with shell script. The dot(.) indicates to
current shell that the command following the dot(.) has to be executed in the same shell i.e. without
the loading of another shell in memory. Or you can also try following syntax to run Shell Script
Syntax:
bash &nbsh;&nbsh; your-shell-program-name
OR
/bin/sh &nbsh;&nbsh; your-shell-program-name

For e.g.
$ bash first
$ /bin/sh first
Note that to run script, you need to have in same directory where you created your script, if
you are in different directory your script will not run (because of path settings), For eg. Your home
directory is ( use $ pwd to see current working directory) /home/vivek. Then you created one script
called 'first', after creation of this script you moved to some other directory lets
say/home/vivek/Letters/Personal
, Now if you try to execute your script it will not run, since script 'first' is in /home/vivek directory,
to Overcome this problem there are two ways First, specify complete path of your script when ever
you want to run it from other directories like giving following command
$ /bin/sh /home/vivek/first

#!/bin /bash/sh

Script.sh

echo “Todays date: `date`”

echo “This months calendar :”

cal `date” +%m20%y”`

echo “my shell: $SHELL”

output:

chmod +x script.sh

./script.sh

Todays date: Mon Feb 10 9:02:41 IST

This months calendar:

February 2019

Su Mo Tu We Th Fr Sa

2 3 4 5 67 8

9 10 11 12 13 14 15
16 17 18 19 20 21 22

23 24 25 26 27 28 29

30

My shell:/bin/sh

STATEMENTS:
Read: The read statement is the shells internal tool for taking input from the user , i.e making
scripts interactive .It is used with one or more variables .Input supplied through the standard input is
read into these variables .when you use a statement like

read name

the script pauses at the point to take input from the keyboard. Whatever you enter is stored in the
variable name .since this is a form of assignment ,no $ is used before name.The script ,emp1.sh uses
read to take a search string and filename from the terminal .

shell scripts accept comments prefixed by # anywhere in a line.

#!/bin/sh
echo “Enter the pattern to be searched : \c”
read pname
echo “Enter the file to be searched to be used : \c”
read flname
echo “searching for $pname from file $flname”
grep “$pname” $flname
grep “selected records shown above”

$emp1.sh
Enter the pattern to be searched :director
Enter the file to be searched to be used :emp.lst
Searching for director from file emp.lst
9876|jai sharma|director|production|12/3/2019|7000
2365|varun sengupta|director|personnel|11/2/2018|7800
selected records shown above
The scripts first asks for a pattern to be entered .Input the string director,which is
assigned to the variable pname. Next, the script asks for the filename ;enter the string emp.lst, which
is assigned to the variable flname.grep the runs with these two variables as arguments.

A single read statemen can be used with one or more variables to let you enter multiple
arguments :

read pname flname

If the number of arguments supplied is less than the number of variables accepting them ,any
leftover variables will simply remain unassigned .

Test: test can be used to test the various file attributes like its type (file,directory or symbolic
link)or its permissions (read,write,execute)Both perl and UNIX system call library also offer these
facilities.

$ls –l emp.lst

-rw-rw-rw- 1 kumar group 870 feb 11.50.10 emp.lst

$ [ -f emp.lst ] ; echo $? An ordinary file?

0 yes

$ [ -x emp.lst ] ;echo $? An executable file ?

1 No

$ [ -w emp.lst ] || echo “False that file is not writable”

False that file is not writable

The ! negates a test,so [ ! –w foo ] negates [ -w foo ] .Using these features you can design a script
,filetest.sh,that accepts the file name as argument and then performs a number of test on it.Test the
script with two filenames-one that doesn’t exist and one that does :

$filetest.sh emp3.lst

File does not exist

$filetest.sh emp.lst

File is blth readable and writable

This completes the discussion on the three domain of test –numeric comparison ,testing of strings
and file attributes .even though we used test with the if statement in all of our examples,test returns
an exit status only ,and can thus be used with any shell construct that uses an exit status.test also
finds wide application in the while statements.

$vi filetest.sh

#!/bin/sh

If [ !-e $1 ] ; then

echo “File does not exist”

elif [ ! –r $1 ] ; then

echo “file is not readable”

elif [ ! –w $1 ] ; then

echo “File is not writable”

else

echo “File is both readable and writable ’’

fi

Test True if File


-f file File exists and is a 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 exist and is a directory
-s file File exist and has a size greater than zero
-e file File exists (korn and Bash only)
-u file File exists and has SUID bit set

If case: The case statement is the second conditional offered by the shell .It doesn’t have a
parallel either in C (switch is similar) or perl. 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 than if. The general syntax of the case statement is as follows :

case expression in

pattern1)commands1 ;;
pattern2) commands2 ;;

pattern3) commands3 ;;

esac

Example :

#!/bin/sh

echo “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 –l ;;
2) ps –f ;;
3) date ;;
4) who ;;
5) exit ;;
*)echo “Invalid option ’’
esac

$ menu.sh

1. List of files
2. proc;esses of user
3. Today’s Date
4. Users of system
5. Quit to Unix
Enter your option :3
Tue Jan 7 18:03:06 IST 2019

Exit: The command is generally run with a numeric arguments.


exit 0 Used when everything went fine
exit 1 Used when something went wrong
These are two very common exit values. You don’t need to place this statement at the
end of every shell script because the shell understands when script execution is complete
.Rather ,it’s quite often used with a command when it fails .
The parameter $? The parameter $? Stores the exit status of the last command .It
has the value 0 if the command succeeds and a nonzero value if it fails . This parameters is
set by exit’s argument. If no exit status is specified ,then $? is set to zero (True).Try using
grep in these ways and you’ll see it returning three different exit values :

$ grep director emp.lst >/dev/null; echo $? ( success )

$ grep manager emp.lst >/dev/null; echo $? ( Failure –in finding pattern)

Expr: COMPUTATION AND STRING HANDLING


The bourn shell can check whether an integer than another ,but it doesn’t have any
computing features at all .It has to rely on the external expr command for that purpose.This
command combines two functions in one: Performs arithmetic operations on integers . Manipulates
strings We’ll use expr to perform both these functions,but with not-very –readable code when it
comes to string handling .If you are using the korn shell or Bash, you have better ways of handling
these things .but you must also understand the helplessness of Bourne. It’s quite possible have to
debug someone else’s script which contains expr.

computation :
expr can perform the four basic arithmetic operations as well as the modulus
(remainder)function:

$ x=3 y=5 Multiple assignments without a;

$ expr 3 + 5

$ expr $x - $y

-2

$ expr 3 \* 5 Asterisk has to be escaped

15

$ expr $y / $x

1 Decimal portion truncated

$ expr 13 % 5

The operand ,be It +, -, * etc , must be enclosed on either side by whitespace.observe that
multiplication operand(*) has to be escaped to prevent the shell from interpreting it as the filename
metacharacter . since expr can handle only integers ,division yields only the integral part.expr is
often used with command substitution to assign a variable .For example ,you can set a variable z to
the sum of two numbers :
$ x=6 y=2 ; z=`expr $x + $y`

$echo $z

LOOPS:
While Loop: The while loop enables you to execute a set of commands repeatedly until some
condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
None of the pattern scanning scripts developed so far offers the user another chance to rectify a
faulty response. Loops let you perform a set of instructions repeatedly.

Syntax:

While condition is true

do

commands

done

#!/bin/sh

a=0

while [ $a -lt 10 ]

do

echo $a

a=`expr $a + 1`

done

output:

4
5

Each time this loop executes, the variable a is checked to see whether it has a value that is less than
10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current
value of a is displayed and later a is incremented by 1.

For loop: The shell’s for loop differs in structure from the ones used in other programming
languages.There is no three-part structure as used in C,awk and perl.Unlike while and until ,for
doesn’t test a condition ,but uses a list instead:

Syntax

For variable in list

do

commands loop body

done

Example:

#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
Output:
0
1
2
3
4
5
Until loop: It is similar to while loop. The only difference is that until statement executes its code block
while its conditional expression is false, and while statement executes its code block while its conditional
expression is true.
Syntax:
until [ condition ]
do
command1
command2
...
....
commandN
done

Example:

#!/bin/bash

i=5

until [ $i –gt 15 ];

do

echo “number $i”

i=$(( i+1 ))

done

Output:
Number 5

Number 6

Number 7

Number 8

Number 9

Number10

Number 11

Number 12

Number 13

Number 14

Number 15

 Manipulating positional parameters-set and shift:


Set:
Some UNIX commands like date produce single-line output . we also pass command output
through filters like grep and head to produce a single line. Recall that we had to use an external command
(cut) to extract a field from the date output

Case `date | cut –d “ ’’ –f1` in


This is overkill;the shell has an internal command to do this job –the set statement.set assigns its
arguments to the positional parameters $1 ,$2, and so on.

$ set 9876 2345 6213

$_

This assigns the value 9876 to the positional parameter $1 ,2345 to $2 and 6213 to $3.It also
sets the other parameters $# and $*.

$ echo “\$1 is $1, \$2 is $2, \$3 is $3”


$1 is 9876, $2 is 2345 $3 is 6213
$ echo “The $# arguments are $*”
The 3 arguments are 9876 2345 6213
Well now use command substitution to extract individual fields from the date output
and without using cut:
$ set `date`
$ echo $*
Wed march 7 09:40:35 IST 2019
$ echo “ The date today is $2 $3, $6”
The date today is march 7 ,2019
The day of the week is available in $1.Using the set features ,the case construct simplifies to
the case $1 in.
Shift:
Many scripts use the first arguments to indicate a separate entity-say a filename.
The other arguments could then represent a series of strings –probably different patterns to be
selected from a file . For this to be possible, for should start its iteration from the parameter
onwards. This is possible with the shift statement.
Shift transfers the contents of a positional parameters to immediate lower numbered
one.This is done as many time as the statement is called . When called once,$2 becomes
$1,$3becomes $2,and so on .Try this on the positional parameters that were previously filled
up with date:
$ echo “$@”
Wed march 7 09:48:44 IST 2003
$ echo $1 $2 $3
Wed march 7
$ shift
$ echo $1 $ 2 $3
March 7 09:48:44
$ shift 2 shift 2 places
09:48:44 IST 2019
 THE HERE DOCUMENT(<<):
There are occasions when the data your program reads is fixed and fairly limited.
The shell uses the << symbols to read data from the same file containing the script. This is
referred to as a here document, signifying that the data is here rather than in a separate file.
Any command using standard input can also take input from a here document.

This features is useful when used with commands that don’t accept a filename as
argument (like the mailx command ,for instance). If the message is short (which any mail
message is normally expected to be),You can have both command and message is normally
expected to be ),You can have both the command and message in the same script:
Mailx sharma << MARK
Your program for printing the invoices has been executed
On `date`, check the print queue (command substitution permitted)
The updated file is known as $flename ( variable evaluation too)
MARK (Nospaces permitted here)
The here document symbol(<<) is followed by three lines of data and a delimiter (the
string MARK).The shell treats every line following command and delimited by Mark as input
to the command .sharma at the other end will see the three lines of message text with the date
inserted by command substitution and the evaluated filename.
The word MARK itself doesn’t show up. When this sequence is placed inside a script,
execution is faster because mailx doesn’t have to read an external file; it’s here.
EXIT STATUS OF A COMMAND
 Every Linux command executed by the shell script or user, has an exit status.
 The exit status is an integer number.
 The Linux man pages stats the exit statuses of each command.
 0 exit status means the command was successful without any errors.
 A non-zero (1-255 values) exit status means command was failure
echo $?
date # run date command
echo $? # print exit status
foobar123 # not a valid command
echo $? # print exit status

$? reads the exit status of the last command executed. After a function returns, $? gives
the exit status of the last command executed in the function.

This is Bash's way of giving functions a "return value." [1] Following the execution of a
pipe, a $? gives the exit status of the last command executed. After a script terminates, a $? from the
command-line gives the exit status of the script, that is, the last command executed in the script,
which is, by convention, 0 on success or an integer in the range 1 - 255 on error.

You might also like