SlideShare a Scribd company logo
UNIX




 Basic Shell Scripting



            Presentation By

                      Nihar R Paital
Shell Types in Unix

   Bourne Shell.
   Bourne Again Shell (bash).
   C Shell (c-shell).
   Korn Shell (k-shell).
   TC Shell (tcsh)




                                 Nihar R Paital
Executing a shell script


   There are many ways of executing a shell script:
     – By passing the shell script name as an argument to the shell. For
       example:
     – sh script1.sh




                                                        Nihar R Paital
Shell Scripts



   A script, or file that contains shell commands, is a shell program
   There are two ways to run a script
          1 By using . (dot) command
   Ex:-
           Scriptname
     – By typing scriptname , if the current directory is part of command
        search path . If dot isn’t in your path then type
     – . /scriptname




                                                        Nihar R Paital
Command-line Editing

Enabling Command-line Editing
There are two ways of entering either editing mode
Add following line in .profile file
  $ set -o emacs
or
    $ set -o vi




                                                     Nihar R Paital
Simple Control Mode Commands


Basic vi Control Mode Commands
Command          Description
 h              Move left one character
 l              Move right one character
 w              Move right one word
 b              Move left one word
 e              Move to end of current word
 0              Move to beginning of line
 ^              Move to first non-blank character in line
 $              Move to end of line

                                                     Nihar R Paital
Entering and Changing Text
Commands for Entering vi Input Mode
Command               Description
 i           Text inserted before current character (insert)
 a           Text inserted after current character (append)
 I           Text inserted at beginning of line
 A           Text inserted at end of line
 R           Text overwrites existing text




                                                  Nihar R Paital
Deletion Commands
   Command        Description
   dh             Delete one character backwards
   dl             Delete one character forwards
   db             Delete one word backwards
   dw             Delete one word forwards
   d$             Delete to end of line
   d0             Delete to beginning of line
   u              undoes the last text modification
    command only
   .              redoes the last text modification
    command.

                                              Nihar R Paital
Moving Around in the History File

   Command         Description
   k or -          Move backward one line
   j or +          Move forward one line
   G               Move to line given by repeat count
   ?string         Search backward for string
   /string         Search forward for string
   n               Repeat search in same direction as
    previous
   N               Repeat search in opposite direction of
    previous


                                              Nihar R Paital
The fc Command

   fc (fix command) is a shell built-in command
   It is used to edit one or more commands with editor, and to
    run old commands with changes without having to type the
    entire command in again
   The fc -l is to lists previous commands.
   It takes arguments that refer to commands in the history file.
    Arguments can be numbers or alphanumeric strings
   To see only commands 2 through 4, type fc -l 2 4
   To see only one command type fc -l 5
   To see commands between ls and cal in history ,type fc -l l c
   To edit , fc command_no


                                                   Nihar R Paital
The fc Command

   With no arguments, fc loads the editor with the most recent command.
   With a numeric argument, fc loads the editor with the command with
    that number.
   With a string argument, fc loads the most recent command starting
    with that string.
   With two arguments to fc, the arguments specify the beginning and
    end of a range of commands,




                                                        Nihar R Paital
Shell Variables.

   Positional Parameters.
   Special Parameters.
   Named variables




                             Nihar R Paital
Positional Parameters. of arguments in command line.
    Acquire values from the position

     –   $1, $2, $3,..$9
     –   sh file1 10 20 30
     –   Ex: Suppose the content of the below file test1.sh is




         #!/bin/ksh
         echo Your arguments are $1 $2 $3


    -Run the file test1.sh as
    $ test1.sh 10 15 20
    Output:
    Your arguments are 10 15 20
                                                                 Nihar R Paital
Special Parameters.

   Shell assigns the value for this parameter.
     – $$ - PID number.
     – $# - Number of Command Line Arguments.
     – $0 – Command Name.
     – $* - Displays all the command line arguments.
     – $? – Exit Status.
     – $- - Shell options
     – $! - Process number of the last background command
     – $@ - Same as $*, except when enclosed in double quotes.




                                                     Nihar R Paital
Exit Status



    Every UNIX command , at the end of its execution returns a status number to
     the process that invoked it.
    Indicates whether or not the command ran successfully.
    An exit status of zero is used to indicate successful completion. A nonzero exit
     status indicates that the program
    failed.
    The shell sets the $? variable to the exit status of the last
     foreground command that was executed.
    The constructs if, while, until and the logical AND (&&)
      and OR (||) operators use exit status to make logical
      decisions:
            0 is a logical "true" (success)
            1 is a logical "false" (failure)
    There are built-in true and false commands which you can
     use.


                                                                 Nihar R Paital
Exit Status

   A shell, like any other process, sets an exit status when it
    finishes
    executing. Shell scripts will finish in one of the following ways:
 Abort - If the script aborts due to an internal errorand exit or return
    command, the exit
    status is that set by those commands.
, the exit status is
    that of the last command (the one that aborted the script).
 End - If the script runs to completion, the exit status is that of the last
    command in the script
 Exit - If the script encounters




                                                            Nihar R Paital
Named Variables.

   User-defined variable that can be assigned a value.
   Used extensively in shell-scripts.
   Used for reading data, storing and displaying it.




                                                          Nihar R Paital
Accepting Data from User.

   read.
     – Accepts input from the user.
     – Syntax : read variable_name.
     – Example :

     $ read sname # This will prompt for user input



Here sname is the user defied variable




                                                      Nihar R Paital
Display Data.

   echo
     – Used to display a message or any data as required by the user.
     – echo [Message, Variable]
     – Example:

      $ echo “IBM.”
      $ echo $sname # This will display the value of sname




                                                       Nihar R Paital
Comment Line

   Normally we use the comment lines for documentation purpose.
   The comment lines are not compiled by the compiler
   For make a line a comment line we use # symbol at the beginning of
    the line

   For Ex:
    # This is the First Program




                                                       Nihar R Paital
test command.

   Used extensively for evaluating shell script conditions.
   It evaluates the condition on its right and returns a true or false exit
    status.
   The return value is used by the construct for further execution.
   In place of writing test explicitly, the user could also use [ ].




                                                             Nihar R Paital
test command (Contd).


   Operators used with test for evaluating numeral data are:
          -eq  Equal To
          -lt  Less than
          -gt  Greater than
          -ge  Greater than or equal to
           -le  Less than or equal to
          -ne  not equal to

   Operators used with test for evaluating string data are:
        str1 = str2  True if both equals
        str1 != str2  True if not equals
        -n str1 True if str1 is not a null string
        -z str1  True if str1 is a null string           Nihar R Paital
test command (Contd).

   Operators used with test for evaluating file data are:



         -f file1  True if file1 exists and is a regular file.
         -d file1  True if file1 exists and is directory.
         -s file1 True if file1 exists and has size greater than 0
         -r file1  True if file1 exists and is readable.
         -w file1  True if file1 exists and is writable.
         -x file1  True if file1 exists and is executable.




                                                             Nihar R Paital
Logical Operators.

   Logical Operators used with test are:

            !  Negates the expression.
            -a  Binary ‘and’ operator.
            -o  Binary ‘or’ operator.




                                            Nihar R Paital
expr command.

   Used for evaluating shell expressions.
   Used for arithmetic and string operations.
     – Example : expr 7 + 3           Operator has to be preceded and followed by a space.

                  would give an output 10.
   When used with variables, back quotes need to be used.




                                                                   Nihar R Paital
expr command.
                     String operations

Expr can perform three important string functions:
 1) Determine the length of the string
 2) Extract a substring
 3) Locate the position of a character in a string
    For manipulating strings ,expr uses two expressions seperated by a
   colon.The string to be worked upon is placed on the left of the : and a
   regular expression is placed on its right.




                                                          Nihar R Paital
1) The length of the string



              $ x="shellscripting"
              $ expr length $x
              $ expr $x : '.*'
              $ expr "unix training" : '.*'




                                              Nihar R Paital
2) Extracting a substring


  Syntax: expr substr string position length
  Substr is a keyword , string is any string

       $ x="IBMIndia"
       $ expr substr $x 2 3


       $ y=unix
       $ expr "$y" : '..(..)'
           O/p :- ix
       $ expr "$y" : '.(..)'
           O/p: - ni
       $ expr " abcdef" : '..(...)'
           O/p:- bcd


                                               Nihar R Paital
3) Locating position of a character



 $ expr index $x chars
   Index is a keyword
   X is a variable
   Chars is any character of a string whose position is to be located
   x=shell
           $ expr index $x e
             O/p:- 3




                                                          Nihar R Paital
Conditional Execution.

   &&
    –    The second command is executed only when first is successful.
    –    command1 && command2
   ||
    –    The second command is executed only when the first is
         unsuccessful.
    –    command1 || command2




                                                        Nihar R Paital
Program Constructs


   if
   for
   while
   until
   case




                     Nihar R Paital
if statement.
   Syntax

       if control command
    then
     <commands>
          else
          <commands>
           fi




                            Nihar R Paital
Ex:if statement.

   1) If [ 10 -gt 5 ]
       then
           echo hi
       else
           echo bye
       fi

   2) If grep "unix" xyz && echo found
      then
          ls -l xyz
      fi




                                          Nihar R Paital
Nihar R Paital
Ad

Recommended

UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
Nihar Ranjan Paital
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
Nihar Ranjan Paital
 
UNIX - Class3 - Programming Constructs
UNIX - Class3 - Programming Constructs
Nihar Ranjan Paital
 
Subroutines
Subroutines
Krasimir Berov (Красимир Беров)
 
Unix shell scripts
Unix shell scripts
Prakash Lambha
 
Shell scripting
Shell scripting
Mufaddal Haidermota
 
Unix
Unix
nazeer pasha
 
Scalar data types
Scalar data types
Krasimir Berov (Красимир Беров)
 
Learning sed and awk
Learning sed and awk
Yogesh Sawant
 
Awk programming
Awk programming
Dr.M.Karthika parthasarathy
 
Chap06
Chap06
Dr.Ravi
 
IO Streams, Files and Directories
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 
Subroutines in perl
Subroutines in perl
sana mateen
 
Shell Scripting
Shell Scripting
Gaurav Shinde
 
Bash shell
Bash shell
xylas121
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
Unix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
Subroutines
Subroutines
primeteacher32
 
Using Unix
Using Unix
Dr.Ravi
 
Bash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
Shankar D
 
Awk essentials
Awk essentials
Logan Palanisamy
 
Airlover 20030324 1
Airlover 20030324 1
Dr.Ravi
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1
Dr.Ravi
 
Syntax
Syntax
Krasimir Berov (Красимир Беров)
 
Pipes and filters
Pipes and filters
bhatvijetha
 
Lecture 22
Lecture 22
rhshriva
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
bokonen
 
Unixshellscript 100406085942-phpapp02
Unixshellscript 100406085942-phpapp02
Ben Mohammed Esskhayri
 

More Related Content

What's hot (20)

Learning sed and awk
Learning sed and awk
Yogesh Sawant
 
Awk programming
Awk programming
Dr.M.Karthika parthasarathy
 
Chap06
Chap06
Dr.Ravi
 
IO Streams, Files and Directories
IO Streams, Files and Directories
Krasimir Berov (Красимир Беров)
 
Subroutines in perl
Subroutines in perl
sana mateen
 
Shell Scripting
Shell Scripting
Gaurav Shinde
 
Bash shell
Bash shell
xylas121
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
Unix And Shell Scripting
Unix And Shell Scripting
Jaibeer Malik
 
Subroutines
Subroutines
primeteacher32
 
Using Unix
Using Unix
Dr.Ravi
 
Bash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
Shankar D
 
Awk essentials
Awk essentials
Logan Palanisamy
 
Airlover 20030324 1
Airlover 20030324 1
Dr.Ravi
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1
Dr.Ravi
 
Syntax
Syntax
Krasimir Berov (Красимир Беров)
 
Pipes and filters
Pipes and filters
bhatvijetha
 
Lecture 22
Lecture 22
rhshriva
 

Viewers also liked (20)

Linux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
bokonen
 
Unixshellscript 100406085942-phpapp02
Unixshellscript 100406085942-phpapp02
Ben Mohammed Esskhayri
 
Trouble shoot with linux syslog
Trouble shoot with linux syslog
ashok191
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
Module 13 - Troubleshooting
Module 13 - Troubleshooting
T. J. Saotome
 
APACHE
APACHE
neftaly quijano tun
 
Advanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
Hector Martinez
 
Linux troubleshooting tips
Linux troubleshooting tips
Bert Van Vreckem
 
unix training | unix training videos | unix course unix online training
unix training | unix training videos | unix course unix online training
Nancy Thomas
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
Dan Morrill
 
25 Apache Performance Tips
25 Apache Performance Tips
Monitis_Inc
 
Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2
Dirk Nachbar
 
Sql server troubleshooting
Sql server troubleshooting
Nathan Winters
 
Tomcat next
Tomcat next
Jean-Frederic Clere
 
Tomcat
Tomcat
Venkat Pinagadi
 
Linux monitoring and Troubleshooting for DBA's
Linux monitoring and Troubleshooting for DBA's
Mydbops
 
Oracle Latch and Mutex Contention Troubleshooting
Oracle Latch and Mutex Contention Troubleshooting
Tanel Poder
 
Cloug Troubleshooting Oracle 11g Rac 101 Tips And Tricks
Cloug Troubleshooting Oracle 11g Rac 101 Tips And Tricks
Scott Jenner
 
Bash shell scripting
Bash shell scripting
VIKAS TIWARI
 
Advanced Bash Scripting Guide 2002
Advanced Bash Scripting Guide 2002
duquoi
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
bokonen
 
Trouble shoot with linux syslog
Trouble shoot with linux syslog
ashok191
 
Karkha unix shell scritping
Karkha unix shell scritping
chockit88
 
Module 13 - Troubleshooting
Module 13 - Troubleshooting
T. J. Saotome
 
Advanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
Hector Martinez
 
Linux troubleshooting tips
Linux troubleshooting tips
Bert Van Vreckem
 
unix training | unix training videos | unix course unix online training
unix training | unix training videos | unix course unix online training
Nancy Thomas
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
Dan Morrill
 
25 Apache Performance Tips
25 Apache Performance Tips
Monitis_Inc
 
Fusion Middleware 11g How To Part 2
Fusion Middleware 11g How To Part 2
Dirk Nachbar
 
Sql server troubleshooting
Sql server troubleshooting
Nathan Winters
 
Linux monitoring and Troubleshooting for DBA's
Linux monitoring and Troubleshooting for DBA's
Mydbops
 
Oracle Latch and Mutex Contention Troubleshooting
Oracle Latch and Mutex Contention Troubleshooting
Tanel Poder
 
Cloug Troubleshooting Oracle 11g Rac 101 Tips And Tricks
Cloug Troubleshooting Oracle 11g Rac 101 Tips And Tricks
Scott Jenner
 
Bash shell scripting
Bash shell scripting
VIKAS TIWARI
 
Advanced Bash Scripting Guide 2002
Advanced Bash Scripting Guide 2002
duquoi
 
Ad

Similar to UNIX - Class1 - Basic Shell (20)

shellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
SHELL PROGRAMMING.pptx
SHELL PROGRAMMING.pptx
Technicaltamila2
 
intro unix/linux 03
intro unix/linux 03
duquoi
 
34-shell-programming.ppt
34-shell-programming.ppt
KiranMantri
 
34-shell-programming asda asda asd asd.ppt
34-shell-programming asda asda asd asd.ppt
poyotero
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
Edureka!
 
Unix - Shell Scripts
Unix - Shell Scripts
ananthimurugesan
 
intro unix/linux 02
intro unix/linux 02
duquoi
 
Advanced linux chapter ix-shell script
Advanced linux chapter ix-shell script
Eliezer Moraes
 
Unit 4 scripting and the shell
Unit 4 scripting and the shell
Bhushan Pawar -Java Trainer
 
Basics of shell programming
Basics of shell programming
Chandan Kumar Rana
 
Basics of shell programming
Basics of shell programming
Chandan Kumar Rana
 
Introduction to shell
Introduction to shell
Arash Haghighat
 
Scripting and the shell in LINUX
Scripting and the shell in LINUX
Bhushan Pawar -Java Trainer
 
Productive bash
Productive bash
Ayla Khan
 
Introduction to UNIX
Introduction to UNIX
Bioinformatics and Computational Biosciences Branch
 
newperl5
newperl5
tutorialsruby
 
newperl5
newperl5
tutorialsruby
 
intro unix/linux 08
intro unix/linux 08
duquoi
 
First steps in C-Shell
First steps in C-Shell
Brahma Killampalli
 
Ad

More from Nihar Ranjan Paital (8)

Oracle Select Query
Oracle Select Query
Nihar Ranjan Paital
 
Useful macros and functions for excel
Useful macros and functions for excel
Nihar Ranjan Paital
 
Unix - Class7 - awk
Unix - Class7 - awk
Nihar Ranjan Paital
 
UNIX - Class2 - vi Editor
UNIX - Class2 - vi Editor
Nihar Ranjan Paital
 
UNIX - Class6 - sed - Detail
UNIX - Class6 - sed - Detail
Nihar Ranjan Paital
 
Test funda
Test funda
Nihar Ranjan Paital
 
Csql for telecom
Csql for telecom
Nihar Ranjan Paital
 
Select Operations in CSQL
Select Operations in CSQL
Nihar Ranjan Paital
 

Recently uploaded (20)

Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 

UNIX - Class1 - Basic Shell

  • 1. UNIX Basic Shell Scripting Presentation By Nihar R Paital
  • 2. Shell Types in Unix  Bourne Shell.  Bourne Again Shell (bash).  C Shell (c-shell).  Korn Shell (k-shell).  TC Shell (tcsh) Nihar R Paital
  • 3. Executing a shell script  There are many ways of executing a shell script: – By passing the shell script name as an argument to the shell. For example: – sh script1.sh Nihar R Paital
  • 4. Shell Scripts  A script, or file that contains shell commands, is a shell program  There are two ways to run a script  1 By using . (dot) command  Ex:-  Scriptname – By typing scriptname , if the current directory is part of command search path . If dot isn’t in your path then type – . /scriptname Nihar R Paital
  • 5. Command-line Editing Enabling Command-line Editing There are two ways of entering either editing mode Add following line in .profile file  $ set -o emacs or  $ set -o vi Nihar R Paital
  • 6. Simple Control Mode Commands Basic vi Control Mode Commands Command Description  h Move left one character  l Move right one character  w Move right one word  b Move left one word  e Move to end of current word  0 Move to beginning of line  ^ Move to first non-blank character in line  $ Move to end of line Nihar R Paital
  • 7. Entering and Changing Text Commands for Entering vi Input Mode Command Description  i Text inserted before current character (insert)  a Text inserted after current character (append)  I Text inserted at beginning of line  A Text inserted at end of line  R Text overwrites existing text Nihar R Paital
  • 8. Deletion Commands  Command Description  dh Delete one character backwards  dl Delete one character forwards  db Delete one word backwards  dw Delete one word forwards  d$ Delete to end of line  d0 Delete to beginning of line  u undoes the last text modification command only  . redoes the last text modification command. Nihar R Paital
  • 9. Moving Around in the History File  Command Description  k or - Move backward one line  j or + Move forward one line  G Move to line given by repeat count  ?string Search backward for string  /string Search forward for string  n Repeat search in same direction as previous  N Repeat search in opposite direction of previous Nihar R Paital
  • 10. The fc Command  fc (fix command) is a shell built-in command  It is used to edit one or more commands with editor, and to run old commands with changes without having to type the entire command in again  The fc -l is to lists previous commands.  It takes arguments that refer to commands in the history file. Arguments can be numbers or alphanumeric strings  To see only commands 2 through 4, type fc -l 2 4  To see only one command type fc -l 5  To see commands between ls and cal in history ,type fc -l l c  To edit , fc command_no Nihar R Paital
  • 11. The fc Command  With no arguments, fc loads the editor with the most recent command.  With a numeric argument, fc loads the editor with the command with that number.  With a string argument, fc loads the most recent command starting with that string.  With two arguments to fc, the arguments specify the beginning and end of a range of commands, Nihar R Paital
  • 12. Shell Variables.  Positional Parameters.  Special Parameters.  Named variables Nihar R Paital
  • 13. Positional Parameters. of arguments in command line. Acquire values from the position  – $1, $2, $3,..$9 – sh file1 10 20 30 – Ex: Suppose the content of the below file test1.sh is #!/bin/ksh echo Your arguments are $1 $2 $3 -Run the file test1.sh as $ test1.sh 10 15 20 Output: Your arguments are 10 15 20 Nihar R Paital
  • 14. Special Parameters.  Shell assigns the value for this parameter. – $$ - PID number. – $# - Number of Command Line Arguments. – $0 – Command Name. – $* - Displays all the command line arguments. – $? – Exit Status. – $- - Shell options – $! - Process number of the last background command – $@ - Same as $*, except when enclosed in double quotes. Nihar R Paital
  • 15. Exit Status  Every UNIX command , at the end of its execution returns a status number to the process that invoked it.  Indicates whether or not the command ran successfully.  An exit status of zero is used to indicate successful completion. A nonzero exit status indicates that the program failed.  The shell sets the $? variable to the exit status of the last foreground command that was executed.  The constructs if, while, until and the logical AND (&&) and OR (||) operators use exit status to make logical decisions: 0 is a logical "true" (success) 1 is a logical "false" (failure)  There are built-in true and false commands which you can use. Nihar R Paital
  • 16. Exit Status  A shell, like any other process, sets an exit status when it finishes executing. Shell scripts will finish in one of the following ways:  Abort - If the script aborts due to an internal errorand exit or return command, the exit status is that set by those commands. , the exit status is that of the last command (the one that aborted the script).  End - If the script runs to completion, the exit status is that of the last command in the script  Exit - If the script encounters Nihar R Paital
  • 17. Named Variables.  User-defined variable that can be assigned a value.  Used extensively in shell-scripts.  Used for reading data, storing and displaying it. Nihar R Paital
  • 18. Accepting Data from User.  read. – Accepts input from the user. – Syntax : read variable_name. – Example : $ read sname # This will prompt for user input Here sname is the user defied variable Nihar R Paital
  • 19. Display Data.  echo – Used to display a message or any data as required by the user. – echo [Message, Variable] – Example: $ echo “IBM.” $ echo $sname # This will display the value of sname Nihar R Paital
  • 20. Comment Line  Normally we use the comment lines for documentation purpose.  The comment lines are not compiled by the compiler  For make a line a comment line we use # symbol at the beginning of the line  For Ex: # This is the First Program Nihar R Paital
  • 21. test command.  Used extensively for evaluating shell script conditions.  It evaluates the condition on its right and returns a true or false exit status.  The return value is used by the construct for further execution.  In place of writing test explicitly, the user could also use [ ]. Nihar R Paital
  • 22. test command (Contd).  Operators used with test for evaluating numeral data are: -eq  Equal To -lt  Less than -gt  Greater than -ge  Greater than or equal to -le  Less than or equal to -ne  not equal to  Operators used with test for evaluating string data are: str1 = str2  True if both equals str1 != str2  True if not equals -n str1 True if str1 is not a null string -z str1  True if str1 is a null string Nihar R Paital
  • 23. test command (Contd).  Operators used with test for evaluating file data are: -f file1  True if file1 exists and is a regular file. -d file1  True if file1 exists and is directory. -s file1 True if file1 exists and has size greater than 0 -r file1  True if file1 exists and is readable. -w file1  True if file1 exists and is writable. -x file1  True if file1 exists and is executable. Nihar R Paital
  • 24. Logical Operators.  Logical Operators used with test are:  !  Negates the expression.  -a  Binary ‘and’ operator.  -o  Binary ‘or’ operator. Nihar R Paital
  • 25. expr command.  Used for evaluating shell expressions.  Used for arithmetic and string operations. – Example : expr 7 + 3 Operator has to be preceded and followed by a space. would give an output 10.  When used with variables, back quotes need to be used. Nihar R Paital
  • 26. expr command. String operations Expr can perform three important string functions:  1) Determine the length of the string  2) Extract a substring  3) Locate the position of a character in a string For manipulating strings ,expr uses two expressions seperated by a colon.The string to be worked upon is placed on the left of the : and a regular expression is placed on its right. Nihar R Paital
  • 27. 1) The length of the string $ x="shellscripting" $ expr length $x $ expr $x : '.*' $ expr "unix training" : '.*' Nihar R Paital
  • 28. 2) Extracting a substring Syntax: expr substr string position length Substr is a keyword , string is any string $ x="IBMIndia" $ expr substr $x 2 3 $ y=unix $ expr "$y" : '..(..)' O/p :- ix $ expr "$y" : '.(..)' O/p: - ni $ expr " abcdef" : '..(...)' O/p:- bcd Nihar R Paital
  • 29. 3) Locating position of a character $ expr index $x chars  Index is a keyword  X is a variable  Chars is any character of a string whose position is to be located  x=shell $ expr index $x e O/p:- 3 Nihar R Paital
  • 30. Conditional Execution.  && – The second command is executed only when first is successful. – command1 && command2  || – The second command is executed only when the first is unsuccessful. – command1 || command2 Nihar R Paital
  • 31. Program Constructs  if  for  while  until  case Nihar R Paital
  • 32. if statement.  Syntax if control command then <commands> else <commands> fi Nihar R Paital
  • 33. Ex:if statement.  1) If [ 10 -gt 5 ] then echo hi else echo bye fi  2) If grep "unix" xyz && echo found then ls -l xyz fi Nihar R Paital