OS_Unit _I_Shell_ARS
OS_Unit _I_Shell_ARS
Shell Scripting
Introduction
Shell
⚫Interface to the user
⚫Command interpreter
⚫Programming features
Shells in Linux
Disadvantages
• Compatibility problems between different platforms.
• Slow execution speed.
• A new process launched for almost every shell command
executed.
The Bourne Again Shell
⚫Abbreviated bash
◼ variable name=value
- 'value' is assigned to given 'variable name'
and Value must be on right side = sign.
- Example:
- $ no=10 # this is ok
- $ 10=no # Error, NOT Ok, Value must be on
right side of = sign.
- To define variable called 'vech' having value
Bus
$ vech=Bus
- To define variable called ‘n’ having value 10
$ n=10
Rules for Naming variable name (Both UDV and System
Variable)
◼ Variable name must begin with Alphanumeric character or
underscore character (_), followed by one or more Alphanumeric
character.
e.g. HOME,SYSTEM_VERSION,vech,no
◼ Don't put spaces on either side of the equal sign when assigning
value to variable.
e.g. $ no=10
$ let X=10+2*7
$ echo $X
24
$ let Y=X+2*4
$ echo $Y
32
• An arithmetic expression can be evaluated by $[expression] or $((expression))
$ echo “$((123+20))”
143
$ VAL=$[123+20]
$ echo “$[10*$VAL]”
1430
Starting Shell Scripting
A Simple Shell Script -
#!/bin/bash
# my first script
echo “hello world”
◆ Save as “my_first_script.sh”
◆ First line: special directive
◆ Second line: comment
Running A Shell Script -
./my_first_script.sh
$PATH
bash my_first_script.sh
Execute permission not required
Starting Shell Scripting
A Simple Shell Script -
1.#!/bin/bash
2.# testfile.sh Comment statement
⚫ Options of sh Command
-n : Read commands, but does not execute them.
-v : Prints the input to the shell as the shell reads it.
-x : Prints command lines and their arguments as they
are executed.
This option is used mostly for debugging.
The read Statement
• Use to get input (data from user) from
keyboard and store (data) to variable.
Syntax:
read variable1, variable2,...variableN
⚫ n helps to keep the cursor at the same line
⚫ Read –p :input and prompt on same line
⚫ only read -> stores in REPLY
⚫ read –t 3 response (timeout)
⚫ read –s password
⚫ read –a names: as an array
⚫ read fname mname lname
#Script to read your name from key-board
echo “Enter any two numbers:"
read n1 n2
n3=`expr $n1 + $n2` # n3=$(($n1 + $n2))
• Syntax:
command1;command2
To run two command with one command line.
Examples:
$ date; who
Will print today's date followed by users who
are currently login.
◼ Note that You can't use
$ date who
for same purpose
Executing commands within script
• echo date
• echo `date`
• echo $(date)
• right_now=$(date)
Why Command Line arguments required
◼ Positional parameters are assigned from the shell’s argument
when it is invoked.
◼ Positional parameter “N” may be referenced as “${N}”, or as
“$N” when “N” consists of a single digit.
◼ Telling the command/utility which option to use.
◼ Informing the utility/command which file or group of files to
process (reading/writing of files).
◼ $ myshell foo bar
$0 $1 $2
0 - Shell Script name i.e. myshell
1 - First command line argument passed to myshell i.e. foo
2- Second command line argument passed to myshell i.e. bar
Command line arguments
• Output: vit
• vit
Conditional execution i.e. && and ||
#!/bin/sh
echo -e "enter two numbers:\n"
read n1 n2
if [ $n1 -gt $n2 ]
then
echo "$n1 is greater"
else
echo "$n2 is greater“ Run it as:
fi $ sh test.sh
enter two numbers:
35
5 is greater
Example
#!/bin/bash
if [ -f /etc/passwd ];
then
cp /etc/passwd .
echo “Done.”
else
echo “This file does not exist.”
exit 1
fi
String data
◼ run it as
$ chmod 755 test.sh
$ ./dsh1.sh 4 5
9
$ sh -x test.sh 4 5
◼ $ SayHello()
{
echo "Hello $LOGNAME, Have a nice day”
return
}
◼ To execute this function just type it name as follows:
$ SayHello
Hello Aparna, Have a nice day.
◼ After restarting your computer you will loss this
SayHello() function, since its created for current
session only.
◼ To overcome this problem ,add your function to
/etc/bashrc file.
◼ To add function to this file you must logon as root.
◼ First logon as root or if you already logon with your
name, and want to move to root account, then use
following command
◼ $ su
◼ Open file /etc/bashrc using vi and goto the end of file
(by pressing shift+G) and type the SayHello()
function:
Functions
#!/bin/bash
hello()
{
echo “You are in function hello()”
}
⚫ ,^ ,$, *, ?, +, [^...]
Other Shell-scripting tools
Sed
⚫ Search and Replace
⚫ Delete
Awk
⚫ Search and process patterns
⚫ Process input streams
Usage of Shell-scripts
Speed improvement
⚫Use/write programs for slow operations
e.g: use grep to speeden searches and awk for
mathematical ops
⚫Optimise loops
⚫Minimise I/O : BASH is slow with files
⚫Use awk, Perl, etc. where speed is reqd.
Keeping scripts small
⚫Modularised scripting
Script to reverse given no
echo “enter any number
read n
rev=0 ;
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd` #echo -n $sd
n=`expr $n / 10`
done
echo "Reverse number is $rev"
Write script to print given numbers sum of all digit
echo “enter any number
read n
sum=0 ;sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digit for number is $sum"
System date wise msg
hr=`date | cut -c12-13`
if [ $hr -lt 12 ]; then
mess="Good Morning $LOGNAME, Have nice
day!“
fi
if [ $hr -gt 12 -a $hr -le 16 ] ;then
mess="Good Afternoon $LOGNAME“
fi
if [ $hr -gt 16 -a $hr -le 18 ]; then
mess="Good Evening $LOGNAME“
fi
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n "$i"
done
echo “”
done
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n "$j”
done
echo “”
done
echo "Stars“
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n " *"
done
echo ""
done for
(( i=5; i>=1; i-- ))
do
for (( j=1; j<=i; j++ ))
do
echo -n " *"
done
echo "" done
MAX_NO=0
echo -n "Enter Number between (5 to 9) : "
read MAX_NO
if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ]
; then
echo "I ask to enter number between 5 and
9, Okay“
exit 1
fi
clear
for (( i=1; i<=MAX_NO; i++ ))
do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " $i"
done
echo ""
done
for (( i=1; i<=MAX_NO; i++ ))
do
for (( s=MAX_NO; s>=i; s-- ))
do
echo -n " "
done
for (( j=1; j<=i; j++ ))
do
echo -n " ."
done
echo " done “
Script to sort n numbers in ascending order
echo “enter array size”
read n
echo “enter array elements”
for (( i = 0; i < n ; i++ ))
do
read nos[$i]
done
# Now do the Sorting of numbers -
for (( i = 0; i < n ; i++ ))
do
for (( j = $i; j < n; j++ ))
do
Script to sort n numbers in ascending order