SlideShare a Scribd company logo
1 of 29
SHELL SCRIPTING
MUFADDAL HAIDERMOTA
INTRODUCTION
 A shell in a Linux operating system takes input from you in the form of commands, processes
it, and then gives an output. It is the interface through which a user works on the programs,
commands, and scripts. A shell is accessed by a terminal which runs it.
Types of Shell
There are two main shells in Linux:
1.The Bourne Shell:The prompt for this shell is $ and its derivatives are listed below:
POSIX shell also is known as sh
Korn Shell also knew as sh
Bourne Again SHell also knew as bash (most popular)
2. The C shell:The prompt for this shell is %, and its subcategories are:
C shell also is known as csh
Tops C shell also is known as tcsh
SHELL SCRIPTING
 Shell scripting is writing a series of command for the shell to execute. It can
combine lengthy and repetitive sequences of commands into a single and simple
script, which can be stored and executed anytime.This reduces the effort required
by the end user.
 For executing the script type bash filename.sh
SAMPLE #1 : Variable
Cannot have spaces around your '=' sign.
Can use bash -x scriptname.sh to trace.
Bash variables are untyped.
SAMPLE #2 : Variable
 scopeVar hasn't been set to any value, so it's blank.
 Give it a value
 When you call scope.sh from your interactive shell, a new shell is
spawned to run the script.This is partly because of the #!/bin/sh line
at the start of the script.
 We need to export the variable for it to be inherited by another
program - including a shell script.
 This is changing the value of scopeVar. But there is no way that this
will be passed back to your interactive shell.Try reading the value of
scopeVar .
 Once the shell script exits, its environment is destroyed. But
scopeVar keeps its value of hello within your interactive shell.
 In order to receive environment changes back from the script, we
must source the script - this effectively runs the script within our
own interactive shell, instead of spawning another shell to run it.
 We can source a script via the "." (dot) command
 Note that in this case, we don't need to export scopeVar.
SAMPLE #1 : Special Variables
There are a set of variables which are set for you already, and most of these cannot have values
assigned to them.
These can contain useful information, which can be used by the script to know about the
environment in which it is running.
The variable $0 is the basename of the program as it was called.
$1 .. $9 are the first 9 additional parameters the script was called with.
The variable $@ is all parameters $1 .. whatever.The variable $*, is similar, but does not
preserve any whitespace, and quoting, so "File with spaces" becomes "File" "with" "spaces".
$# is the number of parameters the script was called with.
Note :
the value of $0 changes depending on how the script was called.
$# and $1 .. $9 are set automatically by the shell.
SAMPLE #2 : Special Variables
We can take more than 9 parameters by using the shift command.
$? -This contains the exit value of the last run command. $? will change with every command
that is executed.
The $$ variable is the PID (Process IDentifier) of the currently running shell.This can be useful
for creating temporary files, such as /tmp/my-script.$$ which is useful if many instances of the
script could be run at the same time, and they all need their own temporary files.
The $! variable is the PID of the last run background process.This is useful to keep track of the
process as it gets on with its job.
IFS(Internal Field Separator) -The default value is SPACETAB NEWLINE.
SAMPLE #1 : Arrays
Array members need not be consecutive or contiguous.
Some members of the array can be left uninitialized.
Gaps in the array are okay.
Zero-based indexing
Bash permits array operations on variables, even if the variables are not explicitly declared as
arrays. Ex :
string=abcABC123ABCabc
echo ${string[@]} abcABC123ABCabc
echo ${string[*]} abcABC123ABCabc
echo ${string[0]} abcABC123ABCabc
echo ${string[1]} No output!
echo ${#string[@]} 1 # One element in the array. #The string itself.
SAMPLE #2 : Arrays
An empty array is not the same as an array with empty elements.
 array0=( first second third )
 array1=( '' ) # "array1" consists of one empty element.
 array2=( ) # No elements . . . "array2" is empty.
Copying an array.
array2=( "${array1[@]}" ) / array2="${array1[@]}"
However, this fails with "sparse" arrays.
SAMPLE #3 : Arrays
SAMPLE #1 : Decision Making
 [ -a file ] → file exists.
[ -d file ] → file exists and is a directory.
[ -f file ] →file exists and is a regular file.
[ -u file ] →file exists and its SUID (set user ID)
bit is set.
[ -g file ] →file exists and its SGID bit is set.
[ -k file ] →file exists and its sticky bit is set.
[ -r file ] →file exists and is readable.
[ -s file ]→ file exists and is not empty.
[ -w file ]→file exists and is writable.
[ -x file ] is true if file exists and is executable.
[ string1 = string2 ] → the strings are equal.
[ string1 != string2 ] →the strings are not equal.
-eq –> is true if int1 is equal to int2.
-ne –> true if int1 is not equal to int2.
-lt –> true if int1 is less than int2.
-le –> true if int1 is less than or equal to int2.
-gt –> true if int1 is greater than int2.
-ge –> true if int1 is greater than or equal to
int2.
if CONDITION; then
COMMANDS;
else
OTHER-COMMANDS
fi
SAMPLE #1 : Loops
SAMPLE #1 : Loop Control
The break command terminates the loop (breaks out of it).
The break command may optionally take a parameter. A plain break terminates only the
innermost loop in which it is embedded, but a break N breaks out of N levels of loop.
continue causes a jump to the next iteration of the loop.
The continue command, similar to break, optionally takes a parameter. A plain continue cuts
short the current iteration within its loop and begins the next. A continue N terminates all
remaining iterations at its loop level and continues with the next iteration at the loop, N levels
above.
SAMPLE #1 : Command
Substitution
 Command substitution allows us to take the
output of a command or program (what would
normally be printed to the screen) and save it as
the value of a variable.To do this we place it
within brackets, preceded by a $ sign.
 Command substitution is nice and simple if the
output of the command is a single word or line. If
the output goes over several lines then the
newlines are simply removed and all the output
ends up on a single line.
SAMPLE #2 : Pattern
Substitution
Syntax :
${parameter/pattern/string}
SAMPLE #1 :Quoting mechanisms
Strings in bash are sequences of characters.
To create a literal string, use single quotes; to create an interpolated string, use
double quotes
SAMPLE #1 : Functions
When writing a suite of scripts, it is often easier to write a "library" of useful functions, and
source that file at the start of the other scripts which use the functions.
A function may return a value in one of four different ways:
I. Change the state of a variable or variables
II. Use the exit command to end the shell script
III. Use the return command to end the function, and return the supplied value to the calling section
of the shell script
IV. echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught
The functions are read in and checked for syntax, but not executed until it is explicitly called.
SAMPLE #1 : Regular Expression
Regular expressions are special characters which help search data, matching complex patterns.
Types of Regular expressions :
Basic Regular expressions, Interval Regular expressions, Extended regular expressions
Symbol Descriptions
. replaces any character
^ matches start of string
$ matches end of string
* matches up zero or
more times the
preceding character
 Represent special
characters
() Groups regular
expressions
? Matches up exactly
one character
Expression Description
{n} Matches the preceding
character appearing 'n'
times exactly
{n,m} Matches the preceding
character appearing 'n'
times but not more
than m
{n, } Matches the preceding
character only when it
appears 'n' times or
more
Expression Description
+ Matches
one or more
occurrence
of the
previous
character
? Matches
zero or one
occurrence
of the
previous
character
SAMPLE #1 : File System
Action Files Folders
Inspect ls ls
View content cat ls
Navigate to cd
Move mv mv
Copy cp cp -r
Create nano mkdir
Delete rm rmdir, rm -r
SAMPLE #1 : User Administration
Command Description
sudo adduser username Adds a user
sudo passwd -l 'username' Disable a user
sudo userdel -r 'username' Delete a user
sudo usermod -a -G GROUPNAME
USERNAME
Add user a to a usergroup
sudo deluser USER GROUPNAME Remove user from a user group
finger Gives information on all logged in user
finger username Gives information of a particular user
SAMPLE #1 : System Performance
 free -m is a command used to show the memory used and free.
 ‘NR==2’ extracts data form the second line. the $3 and $2 act as holders
for the used and total values respectively.
 df -h outputs data related to disk usage and partitions.
 awk ‘$NF outputs the number of fields. However, df -h | awk ‘$NF==”/”
will go to that line which contains the character “/”.
 The $5 will select the field number five from that line.
 This ensures that the command extracts the correct percentage of disk used
 The top -bn1 command will execute the top
command only once (n1 = one iteration) the “b” is
used when we want to use “top” in a bash script or to
output its data to a file.
 “grep load” will output the line which contains the
string “load”.
 $(NF-2) will count the number of fields on that line
and decrement 2, thus outputs field #10.
SAMPLE #1 : System Logging
The logger command sends logging messages to the syslogd daemon, and
consequently provokes system logging.
Contents from a file : logger –f filename
SAMPLE #1 : IO Redirection
Every process in Unix has access to three input/output channels by default: STDIN (standard
input), STDOUT (standard output) and STDERR (standard error).
When writing to STDOUT, the output appears (by default) at the console.
When reading from STDIN, it reads (by default) directly from what the user types into the
console.
When writing to STDERR, the output appears (by default) at the console.
All of these channels can be redirected.
1:stdout, 2:stderr,
SAMPLE #2 : IO Redirection
To dump the contents of a file into STDIN , use the < operator.
To dump the output of a command into a file, use the > operator.
To append to the end of a file, use the >> operator.
To specify the contents of STDIN literally, in a script, use the <<endmarker notation.
To redirect error output (STDERR), use the operator 2>
&>filename – Redirects both stdout and stderr to filename
SAMPLE #1 : Signals & Traps
Number Name Description Used for
0 SIGNULL Null Check access to pid
1 SIGHUP Hangup Terminate; can be trapped
2 SIGINT Interrupt Terminate; can be trapped
3 SIGQUIT Quit Terminate with core dump; can be trapped
9 SIGKILL Kill Forced termination; cannot be trapped
15 SIGTERM Terminate Terminate; can be trapped
24 SIGSTOP Stop Pause the process; cannot be trapped
25 SIGTSTP Terminal stop Pause the process; can be trapped
26 SIGCONT Continue Run a stopped process
SAMPLE #2 : Signals & Traps
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3’ 0 1 2 3
exec 1>logFile.out 2>&1
# Everything below will go to the file ‘logFile.out’
 exec 3>&1 4>&2 - Saves file descriptors.
trap 'exec 2>&4 1>&3’ 0 1 2 3 - Restores file descriptors for particular signals.
exec 1>logFile.out 2>&1 - Redirects stdout to file logFile.out then redirect stderr to stdout.
Quick Guide
https://devhints.io/bash
FOLLOW
https://www.shellscript.sh/quickref.html
https://www.shellscript.sh/hints.html
http://www.tldp.org/LDP/abs/html/abs-guide.html#ARRAYS
http://www.tldp.org/LDP/abs/html/abs-guide.html#IO-REDIRECTION
THANK
YOU

More Related Content

What's hot (20)

Subroutines
SubroutinesSubroutines
Subroutines
 
Awk programming
Awk programming Awk programming
Awk programming
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
Syntax
SyntaxSyntax
Syntax
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Unix ppt
Unix pptUnix ppt
Unix ppt
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awk
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Bash shell
Bash shellBash shell
Bash shell
 
Unix
UnixUnix
Unix
 
Linux Shell Scripting
Linux Shell ScriptingLinux Shell Scripting
Linux Shell Scripting
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
 
Powershell notes
Powershell notesPowershell notes
Powershell notes
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
Chap06
Chap06Chap06
Chap06
 

Similar to Shell scripting

Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
 of 70UNIX Unbounded 5th EditionAmir Afzal .docx of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docxMARRY7
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docxof 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docxadkinspaige22
 
intro unix/linux 08
intro unix/linux 08intro unix/linux 08
intro unix/linux 08duquoi
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docxajoy21
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptxNiladriDey18
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.pptKiranMantri
 
Shell Scripts
Shell ScriptsShell Scripts
Shell ScriptsDr.Ravi
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.pptmugeshmsd5
 

Similar to Shell scripting (20)

Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Shell programming
Shell programmingShell programming
Shell programming
 
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
 
SHELL PROGRAMMING
SHELL PROGRAMMINGSHELL PROGRAMMING
SHELL PROGRAMMING
 
perltut
perltutperltut
perltut
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
 of 70UNIX Unbounded 5th EditionAmir Afzal .docx of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
 
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docxof 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
 
intro unix/linux 08
intro unix/linux 08intro unix/linux 08
intro unix/linux 08
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docx
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.ppt
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
lec4.docx
lec4.docxlec4.docx
lec4.docx
 
Slides
SlidesSlides
Slides
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
 

More from Mufaddal Haidermota (6)

Monad
MonadMonad
Monad
 
User management
User managementUser management
User management
 
Azure lessons
Azure lessonsAzure lessons
Azure lessons
 
Data Literacy
Data LiteracyData Literacy
Data Literacy
 
Queuing theory
Queuing theoryQueuing theory
Queuing theory
 
B.E Project: Detection of Bots on Twitter
B.E Project: Detection of Bots on TwitterB.E Project: Detection of Bots on Twitter
B.E Project: Detection of Bots on Twitter
 

Recently uploaded

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 

Recently uploaded (20)

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 

Shell scripting

  • 2. INTRODUCTION  A shell in a Linux operating system takes input from you in the form of commands, processes it, and then gives an output. It is the interface through which a user works on the programs, commands, and scripts. A shell is accessed by a terminal which runs it. Types of Shell There are two main shells in Linux: 1.The Bourne Shell:The prompt for this shell is $ and its derivatives are listed below: POSIX shell also is known as sh Korn Shell also knew as sh Bourne Again SHell also knew as bash (most popular) 2. The C shell:The prompt for this shell is %, and its subcategories are: C shell also is known as csh Tops C shell also is known as tcsh
  • 3. SHELL SCRIPTING  Shell scripting is writing a series of command for the shell to execute. It can combine lengthy and repetitive sequences of commands into a single and simple script, which can be stored and executed anytime.This reduces the effort required by the end user.  For executing the script type bash filename.sh
  • 4. SAMPLE #1 : Variable Cannot have spaces around your '=' sign. Can use bash -x scriptname.sh to trace. Bash variables are untyped.
  • 5. SAMPLE #2 : Variable  scopeVar hasn't been set to any value, so it's blank.  Give it a value  When you call scope.sh from your interactive shell, a new shell is spawned to run the script.This is partly because of the #!/bin/sh line at the start of the script.  We need to export the variable for it to be inherited by another program - including a shell script.  This is changing the value of scopeVar. But there is no way that this will be passed back to your interactive shell.Try reading the value of scopeVar .  Once the shell script exits, its environment is destroyed. But scopeVar keeps its value of hello within your interactive shell.  In order to receive environment changes back from the script, we must source the script - this effectively runs the script within our own interactive shell, instead of spawning another shell to run it.  We can source a script via the "." (dot) command  Note that in this case, we don't need to export scopeVar.
  • 6. SAMPLE #1 : Special Variables There are a set of variables which are set for you already, and most of these cannot have values assigned to them. These can contain useful information, which can be used by the script to know about the environment in which it is running. The variable $0 is the basename of the program as it was called. $1 .. $9 are the first 9 additional parameters the script was called with. The variable $@ is all parameters $1 .. whatever.The variable $*, is similar, but does not preserve any whitespace, and quoting, so "File with spaces" becomes "File" "with" "spaces". $# is the number of parameters the script was called with. Note : the value of $0 changes depending on how the script was called. $# and $1 .. $9 are set automatically by the shell.
  • 7. SAMPLE #2 : Special Variables We can take more than 9 parameters by using the shift command. $? -This contains the exit value of the last run command. $? will change with every command that is executed. The $$ variable is the PID (Process IDentifier) of the currently running shell.This can be useful for creating temporary files, such as /tmp/my-script.$$ which is useful if many instances of the script could be run at the same time, and they all need their own temporary files. The $! variable is the PID of the last run background process.This is useful to keep track of the process as it gets on with its job. IFS(Internal Field Separator) -The default value is SPACETAB NEWLINE.
  • 8. SAMPLE #1 : Arrays Array members need not be consecutive or contiguous. Some members of the array can be left uninitialized. Gaps in the array are okay. Zero-based indexing Bash permits array operations on variables, even if the variables are not explicitly declared as arrays. Ex : string=abcABC123ABCabc echo ${string[@]} abcABC123ABCabc echo ${string[*]} abcABC123ABCabc echo ${string[0]} abcABC123ABCabc echo ${string[1]} No output! echo ${#string[@]} 1 # One element in the array. #The string itself.
  • 9. SAMPLE #2 : Arrays An empty array is not the same as an array with empty elements.  array0=( first second third )  array1=( '' ) # "array1" consists of one empty element.  array2=( ) # No elements . . . "array2" is empty. Copying an array. array2=( "${array1[@]}" ) / array2="${array1[@]}" However, this fails with "sparse" arrays.
  • 10. SAMPLE #3 : Arrays
  • 11. SAMPLE #1 : Decision Making  [ -a file ] → file exists. [ -d file ] → file exists and is a directory. [ -f file ] →file exists and is a regular file. [ -u file ] →file exists and its SUID (set user ID) bit is set. [ -g file ] →file exists and its SGID bit is set. [ -k file ] →file exists and its sticky bit is set. [ -r file ] →file exists and is readable. [ -s file ]→ file exists and is not empty. [ -w file ]→file exists and is writable. [ -x file ] is true if file exists and is executable. [ string1 = string2 ] → the strings are equal. [ string1 != string2 ] →the strings are not equal. -eq –> is true if int1 is equal to int2. -ne –> true if int1 is not equal to int2. -lt –> true if int1 is less than int2. -le –> true if int1 is less than or equal to int2. -gt –> true if int1 is greater than int2. -ge –> true if int1 is greater than or equal to int2. if CONDITION; then COMMANDS; else OTHER-COMMANDS fi
  • 12. SAMPLE #1 : Loops
  • 13. SAMPLE #1 : Loop Control The break command terminates the loop (breaks out of it). The break command may optionally take a parameter. A plain break terminates only the innermost loop in which it is embedded, but a break N breaks out of N levels of loop. continue causes a jump to the next iteration of the loop. The continue command, similar to break, optionally takes a parameter. A plain continue cuts short the current iteration within its loop and begins the next. A continue N terminates all remaining iterations at its loop level and continues with the next iteration at the loop, N levels above.
  • 14. SAMPLE #1 : Command Substitution  Command substitution allows us to take the output of a command or program (what would normally be printed to the screen) and save it as the value of a variable.To do this we place it within brackets, preceded by a $ sign.  Command substitution is nice and simple if the output of the command is a single word or line. If the output goes over several lines then the newlines are simply removed and all the output ends up on a single line.
  • 15. SAMPLE #2 : Pattern Substitution Syntax : ${parameter/pattern/string}
  • 16. SAMPLE #1 :Quoting mechanisms Strings in bash are sequences of characters. To create a literal string, use single quotes; to create an interpolated string, use double quotes
  • 17. SAMPLE #1 : Functions When writing a suite of scripts, it is often easier to write a "library" of useful functions, and source that file at the start of the other scripts which use the functions. A function may return a value in one of four different ways: I. Change the state of a variable or variables II. Use the exit command to end the shell script III. Use the return command to end the function, and return the supplied value to the calling section of the shell script IV. echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught The functions are read in and checked for syntax, but not executed until it is explicitly called.
  • 18. SAMPLE #1 : Regular Expression Regular expressions are special characters which help search data, matching complex patterns. Types of Regular expressions : Basic Regular expressions, Interval Regular expressions, Extended regular expressions Symbol Descriptions . replaces any character ^ matches start of string $ matches end of string * matches up zero or more times the preceding character Represent special characters () Groups regular expressions ? Matches up exactly one character Expression Description {n} Matches the preceding character appearing 'n' times exactly {n,m} Matches the preceding character appearing 'n' times but not more than m {n, } Matches the preceding character only when it appears 'n' times or more Expression Description + Matches one or more occurrence of the previous character ? Matches zero or one occurrence of the previous character
  • 19. SAMPLE #1 : File System Action Files Folders Inspect ls ls View content cat ls Navigate to cd Move mv mv Copy cp cp -r Create nano mkdir Delete rm rmdir, rm -r
  • 20. SAMPLE #1 : User Administration Command Description sudo adduser username Adds a user sudo passwd -l 'username' Disable a user sudo userdel -r 'username' Delete a user sudo usermod -a -G GROUPNAME USERNAME Add user a to a usergroup sudo deluser USER GROUPNAME Remove user from a user group finger Gives information on all logged in user finger username Gives information of a particular user
  • 21. SAMPLE #1 : System Performance  free -m is a command used to show the memory used and free.  ‘NR==2’ extracts data form the second line. the $3 and $2 act as holders for the used and total values respectively.  df -h outputs data related to disk usage and partitions.  awk ‘$NF outputs the number of fields. However, df -h | awk ‘$NF==”/” will go to that line which contains the character “/”.  The $5 will select the field number five from that line.  This ensures that the command extracts the correct percentage of disk used  The top -bn1 command will execute the top command only once (n1 = one iteration) the “b” is used when we want to use “top” in a bash script or to output its data to a file.  “grep load” will output the line which contains the string “load”.  $(NF-2) will count the number of fields on that line and decrement 2, thus outputs field #10.
  • 22. SAMPLE #1 : System Logging The logger command sends logging messages to the syslogd daemon, and consequently provokes system logging. Contents from a file : logger –f filename
  • 23. SAMPLE #1 : IO Redirection Every process in Unix has access to three input/output channels by default: STDIN (standard input), STDOUT (standard output) and STDERR (standard error). When writing to STDOUT, the output appears (by default) at the console. When reading from STDIN, it reads (by default) directly from what the user types into the console. When writing to STDERR, the output appears (by default) at the console. All of these channels can be redirected. 1:stdout, 2:stderr,
  • 24. SAMPLE #2 : IO Redirection To dump the contents of a file into STDIN , use the < operator. To dump the output of a command into a file, use the > operator. To append to the end of a file, use the >> operator. To specify the contents of STDIN literally, in a script, use the <<endmarker notation. To redirect error output (STDERR), use the operator 2> &>filename – Redirects both stdout and stderr to filename
  • 25. SAMPLE #1 : Signals & Traps Number Name Description Used for 0 SIGNULL Null Check access to pid 1 SIGHUP Hangup Terminate; can be trapped 2 SIGINT Interrupt Terminate; can be trapped 3 SIGQUIT Quit Terminate with core dump; can be trapped 9 SIGKILL Kill Forced termination; cannot be trapped 15 SIGTERM Terminate Terminate; can be trapped 24 SIGSTOP Stop Pause the process; cannot be trapped 25 SIGTSTP Terminal stop Pause the process; can be trapped 26 SIGCONT Continue Run a stopped process
  • 26. SAMPLE #2 : Signals & Traps exec 3>&1 4>&2 trap 'exec 2>&4 1>&3’ 0 1 2 3 exec 1>logFile.out 2>&1 # Everything below will go to the file ‘logFile.out’  exec 3>&1 4>&2 - Saves file descriptors. trap 'exec 2>&4 1>&3’ 0 1 2 3 - Restores file descriptors for particular signals. exec 1>logFile.out 2>&1 - Redirects stdout to file logFile.out then redirect stderr to stdout.

Editor's Notes

  1. Are your classroom colors different than what you see in this template? That’s OK! Click on Design -> Variants (the down arrow) -> Pick the color scheme that works for you! Feel free to change any “You will…” and “I will…” statements to ensure they align with your classroom procedures and rules!