Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
145 views31 pages

Shell Scripts

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

Linux 

Shell Scripts
What is Shell Script ? 

ƒ We have seen some basic shell commands , it’s time to 
move on to scripts. 
ƒ There are two ways of writing shell programs. 
ƒ You can type a sequence of commands and allow the 
shell to execute them interactively.
ƒ You can store those commands in a file that you can 
then invoke as a program. This is known as Shell 
Script.
ƒ We will use bash shell  assuming that the shell has been 
installed as /bin/sh and that it is the default shell for 
your login. 
Why Shell Script ? 

ƒ Shell script can take input from user, file and output 
them on screen.
ƒ Useful to create own commands.
ƒ Save lots of time.
ƒ To automate some task of day today life.
ƒ System administration part can be also automated.
How to write and execute ?

ƒ Use any editor  to write shell script.
ƒ The extension is .sh.
ƒ After writing shell script set execute permission for your 
script.
ƒ chmod  +x  script_name
ƒ Execute your script 
ƒ ./script_name
Shell script format

ƒ Every script starts with the line
ƒ #!/bin/bash
ƒ This indicates that the script should be run in the bash 
shell regardless of which interactive shell the user has 
chosen.
ƒ This is very important, since the syntax of different 
shells can vary greatly.
ƒ # is used as the comment character.
ƒ A word beginning with # causes that word and all 
remaining characters on that line to be ignored.
A sample shell script

#!/bin/bash
echo "Hello User"
echo "See the files in current directory"
ls
Variables
ƒ In Linux (Shell), there are two types of variable:
ƒ System variables ‐ created and maintained by Linux 
itself.
ƒ echo $USER
ƒ echo $PATH
ƒ User defined variables ‐ created and maintained by 
user. 
ƒ All variables are considered and stored as strings, even 
when they are assigned numeric values.
ƒ Variables are case sensitive.     
Variables

ƒ When assigning a value to a variable, just use the name. 
ƒ No spaces on either side of the equals sign.
ƒ var_name=value
ƒ Within the shell we can access the contents of a variable 
by preceding its name with a $. 

myname=A [ use quotes if the value contains spaces ]
myos=Linux
text = 1+2
echo Your name:$myname [ A ]
echo Your   os:$myos [ Linux ]
echo $text [ 1+2 ]
Variables

ƒ If you enclose a $variable expression in double quotes, 
it’s replaced with its value when the line is executed.
ƒ If you enclose it in single quotes, no substitution takes 
place. You can also remove the special meaning of the $ 
symbol by prefacing it with a \.

myvar=”Hello”
echo  $myvar [ Hello ]
echo  “$myvar” [ Hello ]
echo  ‘$myvar’ [ $myvar ]
echo  \$myvar [ $myvar ]
Read

ƒ To read user input from keyboard and store it into a 
variable use read var1,var2,.....varn

#!/bin/bash
echo ‐n  "Enter your name:”
read name
echo ‐n  "Enter your student no:”
read stdno
echo "Your Name:$name”
echo "Your  Age:$stdno”
Shell Arithmetic

ƒ The expr command evaluates its arguments as an 
expression.
ƒ It is commonly used for simple arithmetic operations.

#!/bin/bash
expr 1 + 1
expr 1 ‐ 1
expr 1 \* 1
expr 1 / 1
va r=`expr 1 + 1`
x=1
x=`expr $x + 1`
Shell Arithmetic
If‐Else

if  [ conditiong1 ]; then
statement1
elif [ condition2 ]; then
statement2
else
statement3
fi
ƒ It is must to put spaces between the [ braces and the 
condition being checked. 
ƒ If you prefer putting then on the same line as if, you 
must add a semicolon to separate the test from the 
then.
If‐Else
If‐Else
If‐Else
#!/bin/bash
echo "Enter first number "
read num1
echo "Enter second number"
read num2
if [ $num1 ‐gt $num2 ] ;  then
echo "$num1 is greater than $num2"
elif [ $num1 ‐lt $num2 ] ;  then
echo "$num1 is less than $num2"
else
echo "$num1 and $num2 are equal"
fi
Case

case $var in
condition1)  statement ;;
condition2)  statement ;;
*)  statement3
esac

ƒ Notice that each pattern line is terminated with double 
semicolons  ;; .
ƒ You can put multiple statements between each pattern 
and the next, so a double semicolon is needed to mark 
where one statement ends and the next pattern begins.
Case

#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
case “$timeofday” in
yes) echo “Good Morning”;;
no )  echo “Good Afternoon”;;
y )    echo “Good Morning”;;
n )    echo “Good Afternoon”;;
* )    echo “Sorry, answer not recognized”;;
esac
Case

#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday                                                        
case “$timeofday” in
yes | y | Yes | YES ) echo “Good Morning”;;
n* | N* )                   echo “Good Afternoon”;;
* )                              echo “Sorry, answer not recognized”;;
esac
Command Line arguments

ƒ Command line arguments can be passed to the shell 
scripts. There exists a number of built in variables
ƒ $* ‐ command line arguments
ƒ $# ‐ number of arguments
ƒ $n ‐ nth argument in $*
ƒ ./script_name arg1 arg2 .... argn
For

for  variable in list
do
statement
done

for (( expr1; expr2; expr3 ))
do
statement
done
For

[1] [2]
#!/bin/bash #!/bin/bash
echo "the number of args is  for i in `ls`
$#" do
a=1 echo $i
for i in $* done
do
echo "The $a No arg is $i" [3]
a=`expr $a + 1` for(( i=0;i<=50;i++))
done do
echo $i
done
While

while condition do #!/bin/bash
statements password="abc"
done echo "Enter password"
read pass
while [ $pass != $password ]
do
echo "Wrong Password,Try again"
read  pass
done
echo "Write Password"
Until

until condition do #!/bin/bash
statements password="abc"
done echo "Enter password"
read pass
until [ $pass = $password ]
do
echo "Wrong Password,Try again"
read  pass
done
echo "Write Password"
Functions

ƒ Functions can be defined in the shell and it is very useful 
to structure the code.
ƒ To define a shell function simply write its name followed 
by empty parentheses and enclose the statements in 
braces.
function_name () {
statements
}
ƒ Function must be defined before one can invoke it.
Functions

#!/bin/sh
foo() {
echo “Function foo is executing”
}
echo “script starting”
foo
echo “script ending”

output
script starting
Function foo is executing
script ending
Functions
#!/bin/bash
ƒ When a function is invoked,  showarg()
the parameters to the  {
script [$*, $#, $1, $2] and  a=1
so on are replaced by the  for i in $*
parameters to the function.  do
ƒ When the function finishes,  echo "The $a No arg is $i"
they are restored to their  a=`expr $a + 1`
previous values. done
}
echo "Listing start"
showarg $*
echo "Total:$#"
echo "Listing End"
Functions
ƒ Functions can return numeric values using the return 
command. 
ƒ Functions can also return strings by the following ways.
[1]
f(){  var="123“;  }
f
echo $var

[2]
f(){  echo "123"; }
result="$(f)"
Functions

#!/bin/sh if yes_or_no “$1”
yes_or_no()  then
{ echo “Hi $1, nice name”
echo "Is your name $* ?" else
echo "Enter yes or no:" echo “Never mind”
read x fi 
case “$x” in
y | yes ) return 0;;
n | no ) return 1;;
esac
}
Functions

ƒ Be careful :
ƒ Function calling can be recursive.
f()
{
statements
f
}
f
ƒ The parameter must be passed every time a function 
is invoked either from main or from any other 
functions.
Thanks

You might also like