SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Day 4
Shell scripts of
Name
Ananthi Murugesan
presentation
• Company name
www.ananthim.wordpress.com

Author :- Ananthi Murugesan

2
Introduction
• A shell is a program constructed of shell commands
( $shell,$path,Ls,pwd,mkdir..)
• Shell is an environment for user interaction.But it is not a part
of kernel.
• Shell is just like as BAT files in MS-DOS.
• By default,Bash shell is default shell for Linux.

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

3
Shell script
can take
input from
user, file
and output
them on
screen.

4

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
Shell Scripting
• A script is defined as just a plain text file or ASCII file
• with a set of linux / unix commands.
• Flow of control
• IO facilities

• A shell script can be created using any text editor like
vim,emac,notepad++ etc.

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

5
Features of Shell Script
• Shells are CASE SENSITIVE.
• Shells allows interaction with kernel.
• Shells allow one to create functions and pass arguments to them.

• Shells provide help for each and every command using man or help.
• Helps in automation of tasks and thus time saving

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

6
• Shell script allow use of variables.
• Shell scripts are interpreted directly and are not compiled as cc++ codes.
• Shells provide many features including loop
constructs,arrays,variables,branches and functions.

•

shells provide logic with other utilities like pipelining,redirection etc.

• Shells allow file and directory management features.

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

7
Structure of a script
• #!/bin/bash –it defines that in which shell will be used to run the script.
• # comments –comments can be made by using # symbol in a script.
• Chmod +x script.sh – to tell the linux that file is executable.
• ./script.sh to execute the script.
To check current shell ,type following:
echo $SHELL.

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

8
When to Use Shell Script
Shell scripts can be used for a variety of tasks
•Customizing your work environment
•Every time login to see current date, welcome message etc
•Automating your daily tasks
•To take backup all your programs at the end of the day
•Automating repetitive tasks
•Producing sales report of every month etc
•Executing important system procedures
•Shutdown, formatting a disk, creating a file system on it, mounting
and un mounting the disk etc
•Performing same operation on many files
•Replacing printf with myprintf in all C programs present in a dir etc
www.ananthim.wordpress.com

Author :- Ananthi Murugesan

9
When Not to Use Shell Scripting
When the task :
• is too complex such as writing entire billing system
•Require a high degree of efficiency

•Requires a variety of software tools

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

10
Shell Key words
• These are words whose meaning has already been explained to shell
• We cannot use as variable names
• Also called as reserved words
echo
if
until
trap read
wait set
fi
esac
eval unset
shift
do
continueulimit export
umask readonly for
return

www.ananthim.wordpress.com

else
case
while break exec
done
exit

Author :- Ananthi Murugesan

11
Variables



In Linux (Shell), there are two types of variable:
(1) System variables - Created and maintained by
Linux itself. This type of variable defined in CAPITAL
LETTERS.



(2) User defined variables (UDV) - Created and
maintained by user. This type of variable defined in
lower letters.

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

12


BASH=/bin/bash Our shell name



HOME=/home/vivek Our home directory



LOGNAME=students Our logging name



PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings



PS1=[u@h W]$ Our prompt settings



PWD=/home/students/Common Our current working directory



SHELL=/bin/bash Our shell name



USERNAME=vivek User name who is currently login to this PC

TERM =xterm name of the terminal on which you are working
We can see all the system variables and their values using
$set or env

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

13
how to use a variable

define a variable
DRIVE=drivedrivedrive
FUGA=fugafugafuga
num_of_my_awesome_defition=123456
 reference a variable
echo $DRIVE
echo "$DRIVE-$FUGA"
echo $num_of_my_awesome_definition >> $drove

www.ananthim.wordpress.com

Author :- Ananthi Murugasen

14
Variable – Tips
1. a variable is only string type
abc=1234 # quiv to abc="1234"
it's not a number
2. writing rules
standard definition
abc=hogehoge # it's ok
abc = fugafuga # ERROR! it's a function call
#$1='=', $2='fugafuga'; hint is white-space.
3.explicit value
def='#abc $abc @abc' # equiv: #abc $abc @abc
def="#abc $abc @abc'
# equiv: #abc fugafuga @abc

www.ananthim.wordpress.com

Author :- Ananthi Murugasen

15
4. implicit defined special values
$1 $2 $3 ...
it's params by a function call or run a script with params.
# f(){ echo $1; }
// int main(int ac, char** params) { }
$#
it's number of params
# f(){ echo $#; }
// int main(int ac, char** params) { }

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

16
echo & read commands
echo used to display messages on the screen
read used to accept values from the users, make
programming interactive

eg.
echo “Enter ur name “
read name
echo “Good Morning $name”

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
Command Line Arguments
Shell programs can accept values through
1. read [Interactive –used when there are more inputs]
2. From the command Line when u execute it[Non
interactive- used when only a few inputs are there]

For eg. sh1 20 30

Here 20 & 30 are the command Line
arguments.

Command Line args are stored in Positional parameters
$1 contains the first argument, $2 the second, $3 the third etc.
$0 contains the name of the file, $# stores the count of args
$* displays all the args

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
An example of Command Line args.
#! /bin/bash
echo “Program: $0”

echo “The number of args specified is $#”
echo “The args are $*”

sh sh1 prog1 prog2

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
exit : Script Termination
exit command used to prematurely terminate a program. It can
even take args.

eg.

grep “$1” $2 | exit 2
echo “Pattern found – Job over”

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
The logical operators && and ||
These operators can be used to control the execution of command
depending on the success/failure of the previous command

eg.
grep „director‟ emp1.lst && echo “Pattern found in file”
grep „manager‟ emp2.lst || echo “pattern not found”
or grep „director‟ emp.lst‟ && echo “Pattern found” || echo
“Pattern not found”

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
`for` statement and an array like variable

# it's like an array separated by the space char
values='aaa bbb ccc‘

# like the foreach in Java or for-in in JS
for value in $values
do
echo $value
done

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

22
seq` command
> seq 8
1
2
3
4
5
6
7
8

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

23
`...` <-- it's the back-quote pair, not a single-quote pair('...')
# if use the single-quote pair
> echo 'seq 512 64 768'
seq 512 64 768

# if use the back-quote pair
> echo `seq 512 64 768`
512 576 640 704 768 <-- it's like an array string
the back-quote pattern is like an eval() in JS.
it's run a text as a script code. be cautious!

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

24
`for` statement with `seq` command and ` pattern

it's give a loop with a numeric sequence.
for value in `seq 0 15`
do
echo $value
done

www.ananthim.wordpress.com

Author :- Ananthi Murgesan

25
`while` and `until` statements

● while <-- if true then loop
while true
do
echo '\(^o^)/'
Done
● until <-- if false then loop
until false
do
echo '/(^o^)\'
done

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

26
`test` command for comparison > test
test is used to check a condition and return true or false

Relational operators used by if

Operator

Meaning

-eq

Equal to

-ne

Not equal to

-gt

Greater than

-ge

Gfreater than or equal to

-lt

Less than

-le

Less than or equal to

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

27
test String comparison
test with Strings uses = and !=

String Tests used by test
Test

Exit Status

-n str1

true if str1 is not a null string

-z str1

true if str1 is a null string

s1 = s2true if s1 = s2
s1 != s2

true if s1 is not equal to s2

str1

true if str1 is assigned and not null
www.ananthim.wordpress.com

Author :- Ananthi Murugesan

28
file

tests
File related Tests with test

Test

Exit Status

-e file

True if file exists

-f file

True if fie exists and is a regular file

-r file

True if file exists and is readable

-w file

True if file exists and is writable

-x file

True if file exists and is executable

-d file

True if file exists and is a directory

-s file

True if the file exists and has a size >0

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
`test` command for comparison > test
> test 3 -eq 4 <-- equiv (3 == 4)
> echo $?
1 <-- so false in shell-script
> test 3 -ne 4 <-- equiv (3 != 4)
> echo $?
0 <-- so true in shell-script
> test 3 -gt 4 <-- equiv (3 > 4)
> echo $?
1 <-- so false in shell-script

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

30
If statement
# if.sh
f(){
if test $1 -lt 0
then
echo 'negative'
elif test $1 -gt 0
then
echo 'positive'
else
echo 'zero'
fi
}

www.ananthim.wordpress.com

> source if.sh
>f0
zero
>f1
positive
> f -1
negative

Author :- Ananthi Murugesan

31
Case Statement
# case.sh
f(){
case $1 in
0)
echo 'zero';;
1)
echo 'one';;
[2-9])
echo 'two-nine';;
default)
echo '????'
esac
}

www.ananthim.wordpress.com

> source case.sh
>f0
zerp
>f5
two-nine
> f -1
????

Author :- Ananthi Murugesan

32
expr: Computation
Shell doesn’t have any compute features-depend on expr

expr 3 + 5
expr $x + $y
expr $x - $y
expr $x * $y
expr &x / $y
expr $x % $y

division gives only integers as expr

can handle only integers
x=5
x=`expr $x +1`
echo $x

it will give 6

www.ananthim.wordpress.com

Author :- Ananthi Murugesan
sleep & wait
sleep 100

wait

the program sleeps for 100 seconds

wait for completion of all background processes

wait 138

wait for completion of the process 138

www.ananthim.wordpress.com

Author :- Ananthi Murugesan

Weitere ähnliche Inhalte

Was ist angesagt?

Linux presentation
Linux presentationLinux presentation
Linux presentation
Nikhil Jain
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 

Was ist angesagt? (20)

Basic 50 linus command
Basic 50 linus commandBasic 50 linus command
Basic 50 linus command
 
Linux networking
Linux networkingLinux networking
Linux networking
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Shell Scripting in Linux
Shell Scripting in LinuxShell Scripting in Linux
Shell Scripting in Linux
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awk
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scripting
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU Karnataka
 
Multithreading
Multithreading Multithreading
Multithreading
 
Basics of shell programming
Basics of shell programmingBasics of shell programming
Basics of shell programming
 
Linux presentation
Linux presentationLinux presentation
Linux presentation
 
Linux basics part 1
Linux basics part 1Linux basics part 1
Linux basics part 1
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
Input output redirection linux
Input output redirection linuxInput output redirection linux
Input output redirection linux
 
Introduction to Makefile
Introduction to MakefileIntroduction to Makefile
Introduction to Makefile
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiIntroduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
 
Bash shell
Bash shellBash shell
Bash shell
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
 

Ähnlich wie Unix - Shell Scripts

Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
Dr.Ravi
 

Ähnlich wie Unix - Shell Scripts (20)

Powershell notes
Powershell notesPowershell notes
Powershell notes
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
 
Script presentation
Script presentationScript presentation
Script presentation
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekinge
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
Using Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud EnvironmentsUsing Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud Environments
 
55 best linux tips, tricks and command lines
55 best linux tips, tricks and command lines55 best linux tips, tricks and command lines
55 best linux tips, tricks and command lines
 
Using Unix Commands.pptx
Using Unix Commands.pptxUsing Unix Commands.pptx
Using Unix Commands.pptx
 
Using Unix Commands.pptx
Using Unix Commands.pptxUsing Unix Commands.pptx
Using Unix Commands.pptx
 
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdfLearn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
 
Bash production guide
Bash production guideBash production guide
Bash production guide
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
 
Linux advanced privilege escalation
Linux advanced privilege escalationLinux advanced privilege escalation
Linux advanced privilege escalation
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Getting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfGetting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdf
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 
Unix
UnixUnix
Unix
 
50 Most Frequently Used UNIX Linux Commands -hmftj
50 Most Frequently Used UNIX  Linux Commands -hmftj50 Most Frequently Used UNIX  Linux Commands -hmftj
50 Most Frequently Used UNIX Linux Commands -hmftj
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

Unix - Shell Scripts

  • 1. Day 4 Shell scripts of Name Ananthi Murugesan presentation • Company name
  • 3. Introduction • A shell is a program constructed of shell commands ( $shell,$path,Ls,pwd,mkdir..) • Shell is an environment for user interaction.But it is not a part of kernel. • Shell is just like as BAT files in MS-DOS. • By default,Bash shell is default shell for Linux. www.ananthim.wordpress.com Author :- Ananthi Murugesan 3
  • 4. Shell script can take input from user, file and output them on screen. 4 www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 5. Shell Scripting • A script is defined as just a plain text file or ASCII file • with a set of linux / unix commands. • Flow of control • IO facilities • A shell script can be created using any text editor like vim,emac,notepad++ etc. www.ananthim.wordpress.com Author :- Ananthi Murugesan 5
  • 6. Features of Shell Script • Shells are CASE SENSITIVE. • Shells allows interaction with kernel. • Shells allow one to create functions and pass arguments to them. • Shells provide help for each and every command using man or help. • Helps in automation of tasks and thus time saving www.ananthim.wordpress.com Author :- Ananthi Murugesan 6
  • 7. • Shell script allow use of variables. • Shell scripts are interpreted directly and are not compiled as cc++ codes. • Shells provide many features including loop constructs,arrays,variables,branches and functions. • shells provide logic with other utilities like pipelining,redirection etc. • Shells allow file and directory management features. www.ananthim.wordpress.com Author :- Ananthi Murugesan 7
  • 8. Structure of a script • #!/bin/bash –it defines that in which shell will be used to run the script. • # comments –comments can be made by using # symbol in a script. • Chmod +x script.sh – to tell the linux that file is executable. • ./script.sh to execute the script. To check current shell ,type following: echo $SHELL. www.ananthim.wordpress.com Author :- Ananthi Murugesan 8
  • 9. When to Use Shell Script Shell scripts can be used for a variety of tasks •Customizing your work environment •Every time login to see current date, welcome message etc •Automating your daily tasks •To take backup all your programs at the end of the day •Automating repetitive tasks •Producing sales report of every month etc •Executing important system procedures •Shutdown, formatting a disk, creating a file system on it, mounting and un mounting the disk etc •Performing same operation on many files •Replacing printf with myprintf in all C programs present in a dir etc www.ananthim.wordpress.com Author :- Ananthi Murugesan 9
  • 10. When Not to Use Shell Scripting When the task : • is too complex such as writing entire billing system •Require a high degree of efficiency •Requires a variety of software tools www.ananthim.wordpress.com Author :- Ananthi Murugesan 10
  • 11. Shell Key words • These are words whose meaning has already been explained to shell • We cannot use as variable names • Also called as reserved words echo if until trap read wait set fi esac eval unset shift do continueulimit export umask readonly for return www.ananthim.wordpress.com else case while break exec done exit Author :- Ananthi Murugesan 11
  • 12. Variables  In Linux (Shell), there are two types of variable: (1) System variables - Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS.  (2) User defined variables (UDV) - Created and maintained by user. This type of variable defined in lower letters. www.ananthim.wordpress.com Author :- Ananthi Murugesan 12
  • 13.  BASH=/bin/bash Our shell name  HOME=/home/vivek Our home directory  LOGNAME=students Our logging name  PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings  PS1=[u@h W]$ Our prompt settings  PWD=/home/students/Common Our current working directory  SHELL=/bin/bash Our shell name  USERNAME=vivek User name who is currently login to this PC TERM =xterm name of the terminal on which you are working We can see all the system variables and their values using $set or env www.ananthim.wordpress.com Author :- Ananthi Murugesan 13
  • 14. how to use a variable define a variable DRIVE=drivedrivedrive FUGA=fugafugafuga num_of_my_awesome_defition=123456  reference a variable echo $DRIVE echo "$DRIVE-$FUGA" echo $num_of_my_awesome_definition >> $drove www.ananthim.wordpress.com Author :- Ananthi Murugasen 14
  • 15. Variable – Tips 1. a variable is only string type abc=1234 # quiv to abc="1234" it's not a number 2. writing rules standard definition abc=hogehoge # it's ok abc = fugafuga # ERROR! it's a function call #$1='=', $2='fugafuga'; hint is white-space. 3.explicit value def='#abc $abc @abc' # equiv: #abc $abc @abc def="#abc $abc @abc' # equiv: #abc fugafuga @abc www.ananthim.wordpress.com Author :- Ananthi Murugasen 15
  • 16. 4. implicit defined special values $1 $2 $3 ... it's params by a function call or run a script with params. # f(){ echo $1; } // int main(int ac, char** params) { } $# it's number of params # f(){ echo $#; } // int main(int ac, char** params) { } www.ananthim.wordpress.com Author :- Ananthi Murugesan 16
  • 17. echo & read commands echo used to display messages on the screen read used to accept values from the users, make programming interactive eg. echo “Enter ur name “ read name echo “Good Morning $name” www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 18. Command Line Arguments Shell programs can accept values through 1. read [Interactive –used when there are more inputs] 2. From the command Line when u execute it[Non interactive- used when only a few inputs are there] For eg. sh1 20 30 Here 20 & 30 are the command Line arguments. Command Line args are stored in Positional parameters $1 contains the first argument, $2 the second, $3 the third etc. $0 contains the name of the file, $# stores the count of args $* displays all the args www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 19. An example of Command Line args. #! /bin/bash echo “Program: $0” echo “The number of args specified is $#” echo “The args are $*” sh sh1 prog1 prog2 www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 20. exit : Script Termination exit command used to prematurely terminate a program. It can even take args. eg. grep “$1” $2 | exit 2 echo “Pattern found – Job over” www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 21. The logical operators && and || These operators can be used to control the execution of command depending on the success/failure of the previous command eg. grep „director‟ emp1.lst && echo “Pattern found in file” grep „manager‟ emp2.lst || echo “pattern not found” or grep „director‟ emp.lst‟ && echo “Pattern found” || echo “Pattern not found” www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 22. `for` statement and an array like variable # it's like an array separated by the space char values='aaa bbb ccc‘ # like the foreach in Java or for-in in JS for value in $values do echo $value done www.ananthim.wordpress.com Author :- Ananthi Murugesan 22
  • 23. seq` command > seq 8 1 2 3 4 5 6 7 8 www.ananthim.wordpress.com Author :- Ananthi Murugesan 23
  • 24. `...` <-- it's the back-quote pair, not a single-quote pair('...') # if use the single-quote pair > echo 'seq 512 64 768' seq 512 64 768 # if use the back-quote pair > echo `seq 512 64 768` 512 576 640 704 768 <-- it's like an array string the back-quote pattern is like an eval() in JS. it's run a text as a script code. be cautious! www.ananthim.wordpress.com Author :- Ananthi Murugesan 24
  • 25. `for` statement with `seq` command and ` pattern it's give a loop with a numeric sequence. for value in `seq 0 15` do echo $value done www.ananthim.wordpress.com Author :- Ananthi Murgesan 25
  • 26. `while` and `until` statements ● while <-- if true then loop while true do echo '\(^o^)/' Done ● until <-- if false then loop until false do echo '/(^o^)\' done www.ananthim.wordpress.com Author :- Ananthi Murugesan 26
  • 27. `test` command for comparison > test test is used to check a condition and return true or false Relational operators used by if Operator Meaning -eq Equal to -ne Not equal to -gt Greater than -ge Gfreater than or equal to -lt Less than -le Less than or equal to www.ananthim.wordpress.com Author :- Ananthi Murugesan 27
  • 28. test String comparison test with Strings uses = and != String Tests used by test Test Exit Status -n str1 true if str1 is not a null string -z str1 true if str1 is a null string s1 = s2true if s1 = s2 s1 != s2 true if s1 is not equal to s2 str1 true if str1 is assigned and not null www.ananthim.wordpress.com Author :- Ananthi Murugesan 28
  • 29. file tests File related Tests with test Test Exit Status -e file True if file exists -f file True if fie exists and is a regular file -r file True if file exists and is readable -w file True if file exists and is writable -x file True if file exists and is executable -d file True if file exists and is a directory -s file True if the file exists and has a size >0 www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 30. `test` command for comparison > test > test 3 -eq 4 <-- equiv (3 == 4) > echo $? 1 <-- so false in shell-script > test 3 -ne 4 <-- equiv (3 != 4) > echo $? 0 <-- so true in shell-script > test 3 -gt 4 <-- equiv (3 > 4) > echo $? 1 <-- so false in shell-script www.ananthim.wordpress.com Author :- Ananthi Murugesan 30
  • 31. If statement # if.sh f(){ if test $1 -lt 0 then echo 'negative' elif test $1 -gt 0 then echo 'positive' else echo 'zero' fi } www.ananthim.wordpress.com > source if.sh >f0 zero >f1 positive > f -1 negative Author :- Ananthi Murugesan 31
  • 32. Case Statement # case.sh f(){ case $1 in 0) echo 'zero';; 1) echo 'one';; [2-9]) echo 'two-nine';; default) echo '????' esac } www.ananthim.wordpress.com > source case.sh >f0 zerp >f5 two-nine > f -1 ???? Author :- Ananthi Murugesan 32
  • 33. expr: Computation Shell doesn’t have any compute features-depend on expr expr 3 + 5 expr $x + $y expr $x - $y expr $x * $y expr &x / $y expr $x % $y division gives only integers as expr can handle only integers x=5 x=`expr $x +1` echo $x it will give 6 www.ananthim.wordpress.com Author :- Ananthi Murugesan
  • 34. sleep & wait sleep 100 wait the program sleeps for 100 seconds wait for completion of all background processes wait 138 wait for completion of the process 138 www.ananthim.wordpress.com Author :- Ananthi Murugesan