SlideShare a Scribd company logo
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

More Related Content

What's hot

Bash shell
Bash shellBash shell
Bash shell
xylas121
 
Linux basics
Linux basicsLinux basics
Linux basics
BhaskarNeeluru
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
Manav Prasad
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
vceder
 
Unix Commands
Unix CommandsUnix Commands
Unix Commands
Dr.Ravi
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programming
sudhir singh yadav
 
Unix cheatsheet
Unix cheatsheetUnix cheatsheet
Unix cheatsheet
Dhaval Shukla
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
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
 
Linux intro 5 extra: awk
Linux intro 5 extra: awkLinux intro 5 extra: awk
Linux intro 5 extra: awk
Giovanni Marco Dall'Olio
 
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
Ahmed El-Arabawy
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
abclearnn
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
Prof. Dr. K. Adisesha
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
worr1244
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
Assic 16th Lecture
Assic 16th LectureAssic 16th Lecture
Assic 16th Lecture
babak danyal
 
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
Mahmoud Samir Fayed
 
Basic unix commands
Basic unix commandsBasic unix commands
Basic unix commands
swtjerin4u
 
Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014
Prof. Wim Van Criekinge
 

What's hot (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
 

Viewers also liked

Información campamento multiaventura de judo
Información campamento multiaventura de judoInformación campamento multiaventura de judo
Información campamento multiaventura de judo
Cole Navalazarza
 
Ajicara2
Ajicara2Ajicara2
Ajicara2
guest95bcd36
 
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
Nelson Piedra
 
Guia Oriente
Guia OrienteGuia Oriente
Guia Oriente
salonesdeartistas
 
Expo Universelle 1900
Expo Universelle 1900Expo Universelle 1900
Expo Universelle 1900cab3032
 
Citocinas y diabetes en méxico
Citocinas y diabetes en méxicoCitocinas y diabetes en méxico
Citocinas y diabetes en méxico
Mirian Soon Perez
 
N 20150403 una amenaza para lucy
N 20150403 una amenaza para lucyN 20150403 una amenaza para lucy
N 20150403 una amenaza para lucy
rubindecelis32
 
Justrite Sales Presentation Grainger Inside Sales
Justrite Sales Presentation Grainger Inside SalesJustrite Sales Presentation Grainger Inside Sales
Justrite Sales Presentation Grainger Inside Sales
Hiram Gomez
 
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
 
Dr Khrais_CV
Dr Khrais_CVDr Khrais_CV
Dr Khrais_CV
Dr. Moh Khrais
 
Katalog Tellofix und Wiberg - Suppenhandel
Katalog Tellofix und Wiberg - SuppenhandelKatalog Tellofix und Wiberg - Suppenhandel
Katalog Tellofix und Wiberg - Suppenhandel
Vorname Nachname
 
Patente Europea
Patente EuropeaPatente Europea
Altran digital and mobile wave
Altran digital and mobile waveAltran digital and mobile wave
Altran digital and mobile wave
rdemaestri
 
Windows update
Windows updateWindows update
Windows update
Jhomar1996
 
Net hal ticket no
Net hal ticket noNet hal ticket no
Net hal ticket no
techkrishn
 
Animales de todos tipos belen
Animales de todos tipos belenAnimales de todos tipos belen
Animales de todos tipos belen
losboscos9
 
Clinica de ojos oftalmic laser
Clinica de ojos oftalmic laserClinica de ojos oftalmic laser
Clinica de ojos oftalmic laser
Clinica De Ojos Oftalmic Laser Peru
 

Viewers also liked (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
 

Similar to Advanced linux chapter ix-shell script

SHELL PROGRAMMING
SHELL PROGRAMMINGSHELL PROGRAMMING
SHELL PROGRAMMING
jinal thakrar
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Unix
UnixUnix
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
Sasidhar Kothuru
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
Gaurav Shinde
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Unit VI
Unit VI Unit VI
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 
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)
Cyber Security Infotech Pvt. Ltd.
 
Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands Course 102: Lecture 8: Composite Commands
Course 102: Lecture 8: Composite Commands
Ahmed El-Arabawy
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.ppt
KiranMantri
 
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
Bhavsingh Maloth
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
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
Kel Cecil
 
Raspberry pi Part 25
Raspberry pi Part 25Raspberry pi Part 25
Raspberry pi Part 25
Techvilla
 
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
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
Chandan Kumar Rana
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
Chandan Kumar Rana
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scripting
erbipulkumar
 

Similar to 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
 

Recently uploaded

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Ashish Kohli
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 

Recently uploaded (20)

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 

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