SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Chapter 3
Writing and Executing a shell script
Advanced Linux administration using
Fedora v. 9
Lecturer: Mr. Kao Sereyrath, MScIT (SMU, India)
Director of Technology and Consulting Service (DCD Organization)
ICT Manager (CHC Microfinance Limited)
Contents
Advantage of using shell script1
3
4
5
2 Creating and executing shell script
Learn about variable
Learn about operator
if and case statement
6 for, while and until statement
7 Create function in shell script
Advantage of using shell script
 Hundreds of commands included with Fedora are actually
shell scripts. For example startx command.
 Shell script can save your time and typing, if you routinely
use the same command lines multiple times every day.
 A shell program can be smaller in size than a compiled
program.
 The process of creating and testing shell scripts is also
generally simpler and faster than the development process.
 You can learn more with “Sams Teach Yourself Shell
Programming in 24 Hours”
Creating and Executing shell script
To create shell script :
 You can use vi command. Because it won't wrap text.
 Or you can use nano -w to disable line wrap
 For example, to create myenv file
vi /etc/myenv
To execute shell script :
 First you need to set file permission
chmod +x myenv
Creating and Executing shell script (Cont.)
 To execute myenv file in /etc directory
./myenv
 To enable shell script as your Linux command, first you
need to create bin directory in user home directory. Then
put shell script file into that directory.
mkdir bin
mv /etc/myenv bin
myenv
Learn about variable
 There are 3 types of variable:
– Environment variables: Part of the system
environment, you can use and modify them in your shell
program. For example PATH variable.
– Built-in variables: Unlike environment variables, you
cannot modify them. For example $#, $0
– User variable: Defined by you when you write a shell
script.
Learn about variable (Cont.)
Positional parameter
if [ $# -eq 0 ]
then
echo "Tell me your name please"
else
echo "Welcome "$1
fi
 $# is a positional parameter and $1 is to get first
parameter. You can use $2 to get second parameter.
Learn about variable (Cont.)
Using single quote to escape variable
var="Welcome to Linux"
echo 'The value of $var is '$var
 The output is:
The value of $var is Welcome to Linux
Learn about variable (Cont.)
Using backtick ( ` ) to execute Linux command
ls -l >> myfile.txt
mycount=`wc -l myfile.txt`
echo "File size: "$mycount
 The output is:
File size: 33 myfile.txt
Learn about Operator
Comparison operator
= To compare whether two strings are equal
!= To compare whether two strings are not equal
-n To evaluate whether the string length is greater than zero
-z To evaluate whether the string length is equal to zero
#String comparison
string1="abc"
string2="Abc"
if [ $string1 = $string2 ]
then
echo "string1 equal to string2"
else
echo "string1 not equal to string2"
fi
Learn about Operator (Cont.)
#String comparison
string1="abc"
string2="Abc"
if [ $string1 != $string2 ]; then
echo "string1 not equal to string2"
else
echo "string1 equal to string2"
fi
if [ $string1 ]; then
echo “string1 is not empty”
else
echo “string1 is empty”
fi
Learn about Operator (Cont.)
if [ -n $string2 ]; then
echo “string2 has a length greater than zero”
else
echo “string2 has length equal to zero”
fi
if [ -z $string1 ]; then
echo “string1 has a length equal to zero”
else
echo “string1 has a length greater than zero”
fi
Learn about Operator (Cont.)
Number comparison
-eq To compare Equal
-ge To compare Greater than or equal to
-le To compare Less than or equal to
-ne To compare Not equal
-gt To compare Greater than
-lt To compare Less than
if [ $number1 -gt $number2 ]; then
echo “number1 is greater than number2”
else
echo “number1 is not greater than number2”
fi
Learn about Operator (Cont.)
File operator
-d Check if it is a directory
-f Check if it is a file
-r Check if the file has Read permission
-w Check if the file has Write permission
-x Check if the file has Execute permission
-s Check if file exist and has length greater than zero
Learn about Operator (Cont.)
filename="/root/bin/myfile.txt"
if [ -f $filename ]; then
echo "Yes $filename is a file"
else
echo "No $filename is not a file"
fi
if [ -x $filename ]; then
echo "$filename has Execute permission"
else
echo "$filename has no Execute permission"
fi
if [ -d "/root/bin/dir1" ]; then
echo "It is a directory"
else
echo "No it is not a directory"
fi
Learn about Operator (Cont.)
Logical operator
! To negate logical expression
-a Logical AND
-o Logical OR
if [ -x $filename1 -a -x $filename2 ]; then
echo "$filename1 and $filename2 is executable"
else
echo "$filename1 and $filename2 is not executable"
fi
if [ ! -w $file1 ]; then
echo “$file1 is not writable”
else
echo “$file1 is writable”
fi
if and case statement
if statement syntax
if [ expression ]; then
Statements
elif [ expression ]; then
Statements
else
Statements
fi
Example:
if [ $var = “Yes” ]; then
echo “Value is Yes”
elif [ $var = “No” ]; then
echo “Value is No”
else
echo “Invalid value”
fi
if and case statement (Cont.)
case statement syntax
case str in
str1 | str2)
Statements;;
str3 | str4)
Statements;;
*)
Statements;;
esac
Example:
case $1 in
001 |01 | 1) echo "January";;
02 | 2) echo "February";;
3) echo "March";;
*) echo "Incorrect supplied value";;
esac
for, while and until statement
Example1: for statement
for filename in *
do
cp $filename backup/$filename
if [ $? -ne 0 ]; then
echo “copy for $filename failed”
fi
done
Above example is used to copy all files from current directory
to backup directory. if [ $? -ne 0 ] statement is used to
check status of execution.
for, while and until statement (Cont.)
Example2: for statement
echo "You have passed following parameter:"
i=1
for parlist in $@
do
echo $i" "$parlist
i=`expr $i + 1`
done
If you type myenv domain1 domain2. The result is:
You have passed following parameter:
1 domain1
2 domain2
for, while and until statement (Cont.)
Example: while statement
loopcount=0
while [ $loopcount -le 4 ]
do
useradd "user"$loopcount
loopcount=`expr $loopcount + 1`
done
Above statement is used to create user0, user1, user2, user3,
user4.
for, while and until statement (Cont.)
Example: until statement
loopcount=0
until [ $loopcount -ge 4 ]
do
echo $loopcount
loopcount=`expr $loopcount + 1`
done
Above statement is used to output 0, 1, 2, 3 to display.
Create function in shell script
You can create function by using below example.
myfunc()
{
case $1 in
1) echo "January";;
2) echo "February";;
3) echo "March";;
4) echo "April";;
5) echo "May";;
6) echo "June";;
7) echo "July";;
8) echo "August";;
9) echo "September";;
10) echo "October";;
11) echo "November";;
12) echo "December";;
*) echo "Invalid input";;
esac }
Calling function
myfunc 3
Output is
March
Advanced linux chapter ix-shell script

Weitere ähnliche Inhalte

Was ist angesagt?

Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Unix Commands
Unix CommandsUnix Commands
Unix Commands
Dr.Ravi
 
Unit 7 standard i o
Unit 7 standard i oUnit 7 standard i o
Unit 7 standard i o
root_fibo
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 

Was ist angesagt? (20)

Bash shell
Bash shellBash shell
Bash shell
 
Linux basics
Linux basicsLinux basics
Linux basics
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
Unix Commands
Unix CommandsUnix Commands
Unix Commands
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programming
 
Unix cheatsheet
Unix cheatsheetUnix cheatsheet
Unix cheatsheet
 
Files in php
Files in phpFiles in php
Files in php
 
Unit 7 standard i o
Unit 7 standard i oUnit 7 standard i o
Unit 7 standard i o
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
 
Linux intro 5 extra: awk
Linux intro 5 extra: awkLinux intro 5 extra: awk
Linux intro 5 extra: awk
 
Course 102: Lecture 4: Using Wild Cards
Course 102: Lecture 4: Using Wild CardsCourse 102: Lecture 4: Using Wild Cards
Course 102: Lecture 4: Using Wild Cards
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
 
Assic 16th Lecture
Assic 16th LectureAssic 16th Lecture
Assic 16th Lecture
 
The Ring programming language version 1.5.1 book - Part 38 of 180
The Ring programming language version 1.5.1 book - Part 38 of 180The Ring programming language version 1.5.1 book - Part 38 of 180
The Ring programming language version 1.5.1 book - Part 38 of 180
 
Basic unix commands
Basic unix commandsBasic unix commands
Basic unix commands
 
Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014
 

Andere mochten auch

Expo Universelle 1900
Expo Universelle 1900Expo Universelle 1900
Expo Universelle 1900
cab3032
 
N 20150403 una amenaza para lucy
N 20150403 una amenaza para lucyN 20150403 una amenaza para lucy
N 20150403 una amenaza para lucy
rubindecelis32
 
Flyer_STAR LINES-RoRo_June 2015
Flyer_STAR LINES-RoRo_June 2015Flyer_STAR LINES-RoRo_June 2015
Flyer_STAR LINES-RoRo_June 2015
Veselin Rubcev
 
Social Review "Beauty and Health Care"
Social Review "Beauty and Health Care"Social Review "Beauty and Health Care"
Social Review "Beauty and Health Care"
interactivelabs
 
Animales de todos tipos belen
Animales de todos tipos belenAnimales de todos tipos belen
Animales de todos tipos belen
losboscos9
 

Andere mochten auch (19)

Información campamento multiaventura de judo
Información campamento multiaventura de judoInformación campamento multiaventura de judo
Información campamento multiaventura de judo
 
Ajicara2
Ajicara2Ajicara2
Ajicara2
 
Modelo de Créditos ECTS para ECC - UTPL
Modelo de Créditos ECTS para ECC - UTPLModelo de Créditos ECTS para ECC - UTPL
Modelo de Créditos ECTS para ECC - UTPL
 
Guia Oriente
Guia OrienteGuia Oriente
Guia Oriente
 
Expo Universelle 1900
Expo Universelle 1900Expo Universelle 1900
Expo Universelle 1900
 
Citocinas y diabetes en méxico
Citocinas y diabetes en méxicoCitocinas y diabetes en méxico
Citocinas y diabetes en méxico
 
N 20150403 una amenaza para lucy
N 20150403 una amenaza para lucyN 20150403 una amenaza para lucy
N 20150403 una amenaza para lucy
 
Justrite Sales Presentation Grainger Inside Sales
Justrite Sales Presentation Grainger Inside SalesJustrite Sales Presentation Grainger Inside Sales
Justrite Sales Presentation Grainger Inside Sales
 
Flyer_STAR LINES-RoRo_June 2015
Flyer_STAR LINES-RoRo_June 2015Flyer_STAR LINES-RoRo_June 2015
Flyer_STAR LINES-RoRo_June 2015
 
Social Review "Beauty and Health Care"
Social Review "Beauty and Health Care"Social Review "Beauty and Health Care"
Social Review "Beauty and Health Care"
 
Dr Khrais_CV
Dr Khrais_CVDr Khrais_CV
Dr Khrais_CV
 
Katalog Tellofix und Wiberg - Suppenhandel
Katalog Tellofix und Wiberg - SuppenhandelKatalog Tellofix und Wiberg - Suppenhandel
Katalog Tellofix und Wiberg - Suppenhandel
 
Patente Europea
Patente EuropeaPatente Europea
Patente Europea
 
AVV FACTORING
AVV FACTORINGAVV FACTORING
AVV FACTORING
 
Altran digital and mobile wave
Altran digital and mobile waveAltran digital and mobile wave
Altran digital and mobile wave
 
Windows update
Windows updateWindows update
Windows update
 
Net hal ticket no
Net hal ticket noNet hal ticket no
Net hal ticket no
 
Animales de todos tipos belen
Animales de todos tipos belenAnimales de todos tipos belen
Animales de todos tipos belen
 
Clinica de ojos oftalmic laser
Clinica de ojos oftalmic laserClinica de ojos oftalmic laser
Clinica de ojos oftalmic laser
 

Ähnlich wie Advanced linux chapter ix-shell script

Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
The Korn Shell is the UNIX shell (command execution program, often c.docx
The Korn Shell is the UNIX shell (command execution program, often c.docxThe Korn Shell is the UNIX shell (command execution program, often c.docx
The Korn Shell is the UNIX shell (command execution program, often c.docx
SUBHI7
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scripting
erbipulkumar
 

Ähnlich wie Advanced linux chapter ix-shell script (20)

SHELL PROGRAMMING
SHELL PROGRAMMINGSHELL PROGRAMMING
SHELL PROGRAMMING
 
Shell programming
Shell programmingShell programming
Shell programming
 
Unix
UnixUnix
Unix
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Unit VI
Unit VI Unit VI
Unit VI
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.ppt
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Coming Out Of Your Shell - A Comparison of *Nix Shells
Coming Out Of Your Shell - A Comparison of *Nix ShellsComing Out Of Your Shell - A Comparison of *Nix Shells
Coming Out Of Your Shell - A Comparison of *Nix Shells
 
Raspberry pi Part 25
Raspberry pi Part 25Raspberry pi Part 25
Raspberry pi Part 25
 
The Korn Shell is the UNIX shell (command execution program, often c.docx
The Korn Shell is the UNIX shell (command execution program, often c.docxThe Korn Shell is the UNIX shell (command execution program, often c.docx
The Korn Shell is the UNIX shell (command execution program, often c.docx
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scripting
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Advanced linux chapter ix-shell script

  • 1. Chapter 3 Writing and Executing a shell script Advanced Linux administration using Fedora v. 9 Lecturer: Mr. Kao Sereyrath, MScIT (SMU, India) Director of Technology and Consulting Service (DCD Organization) ICT Manager (CHC Microfinance Limited)
  • 2. Contents Advantage of using shell script1 3 4 5 2 Creating and executing shell script Learn about variable Learn about operator if and case statement 6 for, while and until statement 7 Create function in shell script
  • 3. Advantage of using shell script  Hundreds of commands included with Fedora are actually shell scripts. For example startx command.  Shell script can save your time and typing, if you routinely use the same command lines multiple times every day.  A shell program can be smaller in size than a compiled program.  The process of creating and testing shell scripts is also generally simpler and faster than the development process.  You can learn more with “Sams Teach Yourself Shell Programming in 24 Hours”
  • 4. Creating and Executing shell script To create shell script :  You can use vi command. Because it won't wrap text.  Or you can use nano -w to disable line wrap  For example, to create myenv file vi /etc/myenv To execute shell script :  First you need to set file permission chmod +x myenv
  • 5. Creating and Executing shell script (Cont.)  To execute myenv file in /etc directory ./myenv  To enable shell script as your Linux command, first you need to create bin directory in user home directory. Then put shell script file into that directory. mkdir bin mv /etc/myenv bin myenv
  • 6. Learn about variable  There are 3 types of variable: – Environment variables: Part of the system environment, you can use and modify them in your shell program. For example PATH variable. – Built-in variables: Unlike environment variables, you cannot modify them. For example $#, $0 – User variable: Defined by you when you write a shell script.
  • 7. Learn about variable (Cont.) Positional parameter if [ $# -eq 0 ] then echo "Tell me your name please" else echo "Welcome "$1 fi  $# is a positional parameter and $1 is to get first parameter. You can use $2 to get second parameter.
  • 8. Learn about variable (Cont.) Using single quote to escape variable var="Welcome to Linux" echo 'The value of $var is '$var  The output is: The value of $var is Welcome to Linux
  • 9. Learn about variable (Cont.) Using backtick ( ` ) to execute Linux command ls -l >> myfile.txt mycount=`wc -l myfile.txt` echo "File size: "$mycount  The output is: File size: 33 myfile.txt
  • 10. Learn about Operator Comparison operator = To compare whether two strings are equal != To compare whether two strings are not equal -n To evaluate whether the string length is greater than zero -z To evaluate whether the string length is equal to zero #String comparison string1="abc" string2="Abc" if [ $string1 = $string2 ] then echo "string1 equal to string2" else echo "string1 not equal to string2" fi
  • 11. Learn about Operator (Cont.) #String comparison string1="abc" string2="Abc" if [ $string1 != $string2 ]; then echo "string1 not equal to string2" else echo "string1 equal to string2" fi if [ $string1 ]; then echo “string1 is not empty” else echo “string1 is empty” fi
  • 12. Learn about Operator (Cont.) if [ -n $string2 ]; then echo “string2 has a length greater than zero” else echo “string2 has length equal to zero” fi if [ -z $string1 ]; then echo “string1 has a length equal to zero” else echo “string1 has a length greater than zero” fi
  • 13. Learn about Operator (Cont.) Number comparison -eq To compare Equal -ge To compare Greater than or equal to -le To compare Less than or equal to -ne To compare Not equal -gt To compare Greater than -lt To compare Less than if [ $number1 -gt $number2 ]; then echo “number1 is greater than number2” else echo “number1 is not greater than number2” fi
  • 14. Learn about Operator (Cont.) File operator -d Check if it is a directory -f Check if it is a file -r Check if the file has Read permission -w Check if the file has Write permission -x Check if the file has Execute permission -s Check if file exist and has length greater than zero
  • 15. Learn about Operator (Cont.) filename="/root/bin/myfile.txt" if [ -f $filename ]; then echo "Yes $filename is a file" else echo "No $filename is not a file" fi if [ -x $filename ]; then echo "$filename has Execute permission" else echo "$filename has no Execute permission" fi if [ -d "/root/bin/dir1" ]; then echo "It is a directory" else echo "No it is not a directory" fi
  • 16. Learn about Operator (Cont.) Logical operator ! To negate logical expression -a Logical AND -o Logical OR if [ -x $filename1 -a -x $filename2 ]; then echo "$filename1 and $filename2 is executable" else echo "$filename1 and $filename2 is not executable" fi if [ ! -w $file1 ]; then echo “$file1 is not writable” else echo “$file1 is writable” fi
  • 17. if and case statement if statement syntax if [ expression ]; then Statements elif [ expression ]; then Statements else Statements fi Example: if [ $var = “Yes” ]; then echo “Value is Yes” elif [ $var = “No” ]; then echo “Value is No” else echo “Invalid value” fi
  • 18. if and case statement (Cont.) case statement syntax case str in str1 | str2) Statements;; str3 | str4) Statements;; *) Statements;; esac Example: case $1 in 001 |01 | 1) echo "January";; 02 | 2) echo "February";; 3) echo "March";; *) echo "Incorrect supplied value";; esac
  • 19. for, while and until statement Example1: for statement for filename in * do cp $filename backup/$filename if [ $? -ne 0 ]; then echo “copy for $filename failed” fi done Above example is used to copy all files from current directory to backup directory. if [ $? -ne 0 ] statement is used to check status of execution.
  • 20. for, while and until statement (Cont.) Example2: for statement echo "You have passed following parameter:" i=1 for parlist in $@ do echo $i" "$parlist i=`expr $i + 1` done If you type myenv domain1 domain2. The result is: You have passed following parameter: 1 domain1 2 domain2
  • 21. for, while and until statement (Cont.) Example: while statement loopcount=0 while [ $loopcount -le 4 ] do useradd "user"$loopcount loopcount=`expr $loopcount + 1` done Above statement is used to create user0, user1, user2, user3, user4.
  • 22. for, while and until statement (Cont.) Example: until statement loopcount=0 until [ $loopcount -ge 4 ] do echo $loopcount loopcount=`expr $loopcount + 1` done Above statement is used to output 0, 1, 2, 3 to display.
  • 23. Create function in shell script You can create function by using below example. myfunc() { case $1 in 1) echo "January";; 2) echo "February";; 3) echo "March";; 4) echo "April";; 5) echo "May";; 6) echo "June";; 7) echo "July";; 8) echo "August";; 9) echo "September";; 10) echo "October";; 11) echo "November";; 12) echo "December";; *) echo "Invalid input";; esac } Calling function myfunc 3 Output is March