SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Syntactic analysis in NLP
Syntactic analysis in NLPSyntactic analysis in NLP
Syntactic analysis in NLP
 
Deletion operation in array(ds)
Deletion operation in array(ds)Deletion operation in array(ds)
Deletion operation in array(ds)
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Hotel Management System-Synopsis.pdf
Hotel Management System-Synopsis.pdfHotel Management System-Synopsis.pdf
Hotel Management System-Synopsis.pdf
 
Shift reduce parser
Shift reduce parserShift reduce parser
Shift reduce parser
 
Linked list
Linked listLinked list
Linked list
 
Presentation-Merge Sort
Presentation-Merge SortPresentation-Merge Sort
Presentation-Merge Sort
 
Parse Tree
Parse TreeParse Tree
Parse Tree
 
Specification-of-tokens
Specification-of-tokensSpecification-of-tokens
Specification-of-tokens
 
Recursion
RecursionRecursion
Recursion
 
String matching algorithms(knuth morris-pratt)
String matching algorithms(knuth morris-pratt)String matching algorithms(knuth morris-pratt)
String matching algorithms(knuth morris-pratt)
 
Array data structure
Array data structureArray data structure
Array data structure
 
12 Arreglos
12 Arreglos12 Arreglos
12 Arreglos
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
 

Similar a Unix - Shell Scripts

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 linersKirk Kimmel
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeProf. Wim Van Criekinge
 
Shell Scripts
Shell ScriptsShell Scripts
Shell ScriptsDr.Ravi
 
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 Environmentsahamilton55
 
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 linesArif Wahyudi
 
Using Unix Commands.pptx
Using Unix Commands.pptxUsing Unix Commands.pptx
Using Unix Commands.pptxHarsha Patel
 
Using Unix Commands.pptx
Using Unix Commands.pptxUsing Unix Commands.pptx
Using Unix Commands.pptxHarsha Patel
 
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.pdfClapperboardCinemaPV
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentationbrian_dailey
 
Linux advanced privilege escalation
Linux advanced privilege escalationLinux advanced privilege escalation
Linux advanced privilege escalationJameel Nabbo
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptxNiladriDey18
 
Getting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfGetting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfssuserd254491
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With YouDalibor Gogic
 
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)Jude A. Goonawardena
 

Similar a Unix - Shell Scripts (20)

Powershell notes
Powershell notesPowershell notes
Powershell notes
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
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)
 
Shell programming
Shell programmingShell programming
Shell programming
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 

Último

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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, ...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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...Jeffrey Haguewood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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 FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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, Adobeapidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 

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