SlideShare uma empresa Scribd logo
1 de 72
Unix Shell Scripting



                By
         OpenGurukul.com
Free/Open Source Software Laboratory
Unix Shell Scripting




 Module : Introduction




      www.opengurukul.com   2
Introduction: Shell Program

On Unix systems, shell program acts as an interface between user
and operating system.

The shell program is executed for a user when a user logs in by
scanning /etc/passwd file (last entry has the shell program
name).

The most common used shell program is /bin/sh. On different
flavours of unix, /bin/sh may be a symbolic link or hard link to
actual scripting program.
                            www.opengurukul.com                    3
Introduction: Shell Program

The current shell program that is in use is stored in environment
variable SHELL.

To find the current shell program, use following command

$ echo $SHELL

/bin/bash

$


                          www.opengurukul.com                       4
Introduction: Popular Shell Programs
Shells which are more popular are -
i) bourne again shell (bash),
ii) korn shell (ksh)
iii) c shell (csh).
Linux uses bash (Bourne again shell) by default.
AIX uses korn shell by default.
There are other shells like posix shell, ksh93 etc.
The shell programs that are supported on the systems are
stored in the file /etc/shells on Linux.
                        www.opengurukul.com                5
Shell Scripting: Introduction : Shell
                   Supported

To find shells which are supported on your Linux system.
 $ cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/zsh
$


                       www.opengurukul.com                 6
Shell Scripting: Introduction : Shell Script
                  Extension

The shell scripts generally ends with an extension .sh
  (for korn and bourne shell).
It is not mandatory to have an extension.




                      www.opengurukul.com                7
Shell Scripting: Introduction : Shell Script

A sequence of command that we generally type on the
command prompt can be placed in a file and all the commands
can be executed at one shot.
The file which contains commands to be interpreted by shell
program is called shell script.
The first line in the shell script is generally.
#!/bin/sh
It indicates that /bin/sh should be used to interpret the lines in
the file.
                             www.opengurukul.com                     8
Shell Scripting: Introduction : Create Shell
                    Script

Write a sequence of commands you would like to execute
in a file.
Ensure that the first line indicates the location of interpreter.
Example :
#!/bin/sh
# Example : hello_world.sh


echo Hello World

                          www.opengurukul.com                   9
Shell Scripting: Introduction : Execute
       Permissions on the Shell Script

The shell script can be made executable by using
$ chmod +x script_name.sh




                       www.opengurukul.com         10
Shell Scripting: Introduction: Execute the
                   Shell Script


$ sh ./hello_world.sh


Hello World


$




                        www.opengurukul.com      11
Shell Scripting: Introduction: Exit Status

The exit command terminates a script.
The exit command can return a value, which is available to
the script's parent process.
Exit status of last command is stored in $?
When script ends with exit that has no parameter, exit
status of the script is the exit status of the last command
executed in the script.
Equivalent of a bare exit is exit $? or even just omitting the
exit.

                          www.opengurukul.com                    12
Shell Scripting: Introduction: Exit Status

Significance of Value of Exit Status
      0 indicates successful execution.
      non-0 indicates failed execution.
Example : Success & Failure
Failure:                                Success:
$ ls /file/does/not/exist               $ ls > /dev/null
$ echo $?                               $ echo $?
1                                       0
$                                       $




                              www.opengurukul.com          13
Shell Scripting: Introduction: Comments
                   Single Line

The character "#" (hash) is used to add     # Example : comments.sh
single line comment in a shell script.
Anything that follows # is a comment.       # This is a comment.




                                  www.opengurukul.com                 14
Shell Scripting: Introduction: Comments
                  Multple Line

The multi-line comment is              # Example : comment_multi.sh
created in shell script using ':'
                                       : ' i am
followed by a comment in
single quotes.                         a multi
                                       line
Donot forget to put a space            Comment '
between : (colon) and ' (single
quote).




                             www.opengurukul.com                  15
Unix Shell Scripting




  Module : Variables




      www.opengurukul.com   16
Shell Scripting: Variables: List

To see the list of variables such as PATH, HOME etc, you can use
'env' command.

$ env
...
PATH=/bin:/sbin:/home/sachin/bin
HOME=/home/sachin
SHELL=/bin/bash
...
$




                             www.opengurukul.com                   17
Shell Scripting: Variables : Export
New variables can be instantiated using
variable_name = variable_value
Variables are referenced using either $variable_name or $
{variable_name}.




                           www.opengurukul.com              18
Shell Scripting: Variables : Export: example

Example :                           Example :
                                   $ export A=a
$ MYNAME=matsya                    $ echo $A123 # no output
$ export MYNAME                    $echo ${A}123
(or)                               A123
$ export MYNAME=matsya             $

$ echo $MYNAME




                         www.opengurukul.com                  19
Shell Scripting : Variables : Single
      Quote vs Double Quote
In single quote, variable values are not expanded.
In double quote, variables values will expand.
We can use  (escape sequence) before $ to remove
 special meaning.




                      www.opengurukul.com            20
Shell Scripting : Variables : Single
Quote vs Double Quote : Example
#!/bin/sh
# Example : quote.sh


export USER=matsya1


echo without quotes : $USER                  # prints matsya1
echo "double quotes : $USER"                 # prints matsya1
echo 'single quote: $USER'                   # prints $USER
                       www.opengurukul.com                      21
echo "escape sequence: $USER" # prints $USER
Shell Scripting: Variables : Data Types

Shell Variables are untyped.
We can use the same variable to store integer and string.
Example :
   x=123;
   x="hello"




                       www.opengurukul.com                  22
Shell Scripting: Variables: Integer Variables

declare -i variable_name statement can be used to create integer
variables.
Program:                         Output:
    $ cat integer_variables.sh        $ sh integer_variables.sh
    #!/bin/sh                         count : 10
    declare -i count                  count : 0
    count=10                          $
    echo "count : $count"
    count="hello"
    echo "count : $count"
    $                       www.opengurukul.com                    23
Shell Scripting: Variables : Read-Only
                    Variables

declare -r var1 works the same as Program:
readonly var1, used to create         $ cat -n readonly_variable.sh
read-only variable.                   #!/bin/sh
                                              declare -r count=10
                                              echo $count
                                              count=20
                                              echo $count
                                              $
                                       Output:
                                              $ sh readonly_variable.sh
                                              10
                                              readonly_variable.sh: line 5: count:
                             www.opengurukul.com                                  24
                                                 readonly variable
Shell Scripting: Variables : The read
                    command

read variable_name will store the      Program :
value read from keyboard into
variable_name
                                      # Example : read_cmd.sh
                                      echo "Enter your name "
                                      read name
                                      echo "Your name is $name"

                                      Output :
                                       $ sh read_cmd.sh


                                       Enter your name Matsya Technologies

                            www.opengurukul.com                              25
                                       Your name is Matsya Technologies
Shell Scripting: Variables : REPLY Variable

The read command without a              Program :
variable name will store the value      # read_cmd_reply.sh
entered from keyboard into a built-
in variable REPLY.
                                        echo "Enter your name"
                                        read
                                        echo "Your name is $REPLY"
                                        Output :
                                        $ sh read_cmd_reply.sh


                                        Enter your name Matsya Tech
                             www.opengurukul.com                      26
Unix Shell Scripting




Module : Program Arguments




        www.opengurukul.com   27
Shell Scripting: Program Arguments
Script Name
 $0 is special argument and it contains name of the script itself.

Arguments
$1 is the first argument
$2 is the second argument and so on.

NOTE
To reference to 10th argument, we must use curly braces
around it.

E.g. ${10}.                www.opengurukul.com                       28
Shell Scripting: Program Arguments: Special
              Built-in Variables

$# represents the parameter count.
   Useful for controlling loop constructs that need to
    process each parameter.
$@ expands to all the parameters separated by spaces.
   Useful for passing all the parameters to some other
     function or program.
$$ expands to the process id of the shell that invoked the
  script.
   Useful for creating unique temporary filenames relative
    to this instantiation of the script.
                         www.opengurukul.com              29
Shell Scripting: Program
             Arguments: Example
Program:                                    Output :


# Example : prog_arg.sh                     $ sh prog_arg.sh swathi matsya
echo 'PID : $$ = ' $$                       PID : $$ = 4531
echo 'prog name : $0 = ' $0                 prog name : $0 = prog_arg.sh
echo 'prog: param count : $# = ' $#         prog: param count : $# = 2
echo 'prog: params : $* = ' $*              prog: params : $* = swathi matsya
echo 'prog: first param : $1 = ' $1         prog: first param : $1 = swathi
                                            $


                                 www.opengurukul.com                            30
Shell Scripting: Program
           Arguments: $@ and $*
$@ behaves like $* except that         Program :
  when quoted the arguments are
                                       # example : d_at.sh
  broken up properly if there are
  spaces in them.                      for var in ”$@”
                                       do
                                           echo "$var"
                                       done :
                                       Output
                                       $ sh d_at.sh 1 2 '3 4'
                                       1
                                       2
                                       34
                            www.opengurukul.com                 31
                                       $
Shell Scripting: Program
Arguments: $@ and $* : Example $*
Program :                                   Program :
# example : d_star_quote.sh                 # example : d_star_noquotes.sh
for var in ”$*”                             for var in $*
do                                          do
    echo "$var"                                 echo "$var"
done :
Output                                      done :
                                            Output


$ sh d_star_quote.sh 1 2 '3 4'              $ sh d_star_noquotes.sh 1 2 '3 4'
1234                                        1
$                                           2
                                 www.opengurukul.com                            32
                                            3
Shell Scripting : Program Arguments:
        $@ and $* : Example

# $@ in double quotes : correct way        # $* in double quotes
dat_dq() {                                 dstar_dq() {
echo '$@ in double quotes : '              echo '$* in double quotes : '
for var in "$@" ; do
                                           for var in "$*" ; do
    echo $var
                                               echo $var
done
                                           done
}
                                           }
# $@ in no quotes
                                www.opengurukul.com                        33
dat_nq() {
$ sh dstar_dat.sh
# $@ in no quotes                           $@ in double quotes :
dstar_nq() {                                1
echo '$* without any quotes : '             23
for var in $* ; do                          4
    echo $var                               $@ without any quotes :
done                                        1
}                                           2
                                            3
dat_dq 1 '2 3' 4                            4
dat_nq 1 '2 3' 4                             $* without
                                  www.opengurukul.com     any quotes :   34
Shell Scripting: Program Arguments : shift
                  command

Shift
The shift command can be used to shift arguments to left side.
We can specify a count and we lose that many arguments on the left
side. For a shift of 1, $2 becomes $1 and so on.
For a shift of 2, $3 will become $1.
It is useful to process arguments in a loop using a single variable to
reference to argument one by one.




                             www.opengurukul.com                         35
Shell Scripting: Program
          Arguments: shift command:
                   Example
Program :                                  Output :
echo 'prog: param count : $# = ' $#
echo 'prog: params : $* = ' $*             $ sh prog_arg_shift.sh 10 20 30 40
                                           prog: param count : $# = 4
shift                                      prog: params : $* = 10 20 30 40
                                           after shift
echo "after shift"                         prog: param count : $# = 3
echo 'prog: param count : $# = ' $#        prog: params : $* = 20 30 40
echo 'prog: params : $* = ' $*             after shift 2
                                           prog: param count : $# = 1
shift 2                          www.opengurukul.com params
                                            prog:             : $* = 40         36
Unix Shell Scripting




    Module : Misc




      www.opengurukul.com   37
Shell Scripting: Misc : Command
                    Substitution

In a shell script, the output of a command can be substituted in place
of command name using following syntax.
$(command)
`command`
Such command will be executed in a sub-shell.
The standard output from sub shell will be used in the place of
command when the command completes.




                             www.opengurukul.com                         38
Shell Scripting: Misc : Command
              Substitution : Example

Program :                             Output :
# example : cmd_subst.sh
                                      $ sh cmd_subst.sh 10 20
a=$1                                  sum : 30
b=$2                                  sum : 30
                                      $
total=$(expr $a + $b)
echo "sum : $total"


total=`expr $a + $b`
echo "sum : $total"        www.opengurukul.com                  39
Shell Scripting: Misc : Arithmetic Expansion
Arithmetic expansion is also allowed and comes in the form:
$((expression))
The value of the expression will replace the substitution.
Example : will echo "8" to stdout.
#!/bin/sh
echo $((1+3+4))




                             www.opengurukul.com              40
Shell Scripting: Misc : Arithmetic
             Expansion : Example

Program :                              Output :
# example : arith_expr.sh
                                       $ sh ./arith_expr.sh 40 50
x=$1                                   90
y=$2                                   90
                                       90
echo $(expr $x + $y)                   $


echo $(($x + $y))
                            www.opengurukul.com                     41
Unix Shell Scripting




Module : Test Command




      www.opengurukul.com   42
Shell Scripting: Test Command
The test command or [ expression ] is used to check if an expression is true. If it is
true, 0(zero) is returned otherwise non-zero is returned.


$ test 1 -eq 1 # test equal to
$ echo $?
0
$


$ test 1 -eq 10 # test not equal to
$ echo $?
1
$
                                    www.opengurukul.com                                  43
Shell Scripting: Test Command : Example

Program :                                Output :


# example : test_cmd.sh                  $ sh test_cmd.sh
if test 1 -eq 1 ; then                   test succeeded
     echo "test succeeded";              $
fi




                              www.opengurukul.com           44
Shell Scripting: Test Command: Numbers

Use test command to compare numbers
Numeric Test Operators
-eq = equal to
-ne = not equal to
-lt = less than


-le = less than or equal to


-gt = greater than
                          www.opengurukul.com   45
Shell Scripting: Test Command: Numbers

Program :                                  Output :
a1=$1
op=$2                                      $ sh test_cmd_num.sh 50 -eq 60
a2=$3
if test ${a1} $op ${a2}; then              false
     echo "true"
else                                       false
     echo "false"
fi                                         $ sh test_cmd_num.sh 50 -eq 50
if [ ${a1} $op ${a2} ]; then
     echo "true"
                                           true
else
     echo "false"
                                           true
fi                              www.opengurukul.com                         46
Shell Scripting: Test Command: Strings
String Tests
Equality                            s1 = s2
Inequality                          s1 != s2
Zero (Length is zero)               -z str
Non-zero (Length is non-zero)       -n str




                                www.opengurukul.com   47
Shell Scripting: Test Command: Strings

Program :                              Output :

# example : test_cmd_str.sh
                                       $ sh test_cmd_str.sh in = in
x=$1
op=$2                                  true
y=$3                                   $

if [ $x $op $y ]; then
                                       $ sh test_cmd_str.sh in != out
   echo "true"
                                       true
else
   echo "false"                        $
fi
                                         $ sh test_cmd_str.sh
                              www.opengurukul.com               in != in   48
Shell Scripting: Test Command : Files
The test command can also be used to figure out the file type.
File Exists                         -e file
Normal File (Not a directory)       -f file
Directory                           -d file
Symbolic Link                       -h file
Pipe                                -p file
Character Device File               -c file
Block Device File                   -b file
Socket File                         -S file
Writable                            -w file
Readable                            -r file
Executable                          -x file
Non-Empty file                      -s file
                                www.opengurukul.com              49
Shell Scripting: Test Command : Files :
                    Example

Program :                            Output :
# example : test_cmd_file.sh
file=$1
                                     $ sh test_cmd_file.sh
                                       /bin/bash
if [ -d $file ] ; then
                                         /bin/bash is a regular file
    echo "$file is a directory"
                                         $
elif [ -f $file ] ; then
    echo "$file is a regular file"
else                                     $ sh test_cmd_file.sh /home
   echo "$file type not known";          /home is a directory
fi
                                         $
                              www.opengurukul.com                      50
Shell Scripting: Test Command : Logical
                 Operators

NOT    ! expr
AND    expr1 -a expr2
OR     expr1 -o expr2




                   www.opengurukul.com     51
Shell Scripting: Test Command : Logical
             Operators : Example

Program:                                  Output :
# example:
  test_cmd_logical.sh
                                          $ sh test_cmd_logical.sh 5 4 3
                                          5 is biggest
x=$1
                                          $
y=$2
z=$3


# if test $x -lt $y
if [ $x -gt $y -a $x -gt $z ];www.opengurukul.com
                               then                                    52
Unix Shell Scripting




Module : Control Structures




        www.opengurukul.com   53
Shell Scripting: Control Structures : if
                     construct
The format of if else fi is.


if test condition1
then
       List of commands1
elif test condition2
then
       List of commands2
elif test condition3
then
       List of commands3       www.opengurukul.com   54

else
Shell Scripting: Control Structures : if
                      example

Program :                             Output :


# example : if_construct.sh           $ sh if_construct.sh /var
                                      /var: found
file=$1                               $
if [ -e $file ]
then                                  $ sh if_construct.sh /not
 echo "$file: found"                  /not: not found
else                                  $
                           www.opengurukul.com                    55
 echo "$file: not found"
Shell Scripting: Control Structures: while

The While...Do has the following generic form:
while test condtion
do
  series of commands
done



                   www.opengurukul.com           56
Shell Scripting: Control Structures: while :
                   example

Program :                             Output :
# example : while_construct.sh
K=$1                                  $ sh while_construct.sh 5 9
LIMIT=$2                              5
                                      6
while test $K -le $LIMIT
                                      7
do
                                      8
 echo "$K"
 K=$(( K + 1 ))                       9
done                                  $

                           www.opengurukul.com                      57
Shell Scripting: Control Structures: for

The syntax of the for command is:

for variable in list of values
do
     list of commands
done


                     www.opengurukul.com      58
Shell Scripting: Control Structures: for :
                     Example

Program :                                Output :
# example : for_loop.sh
for K in 20 40 60                        $ sh for_loop.sh
do
                                         20
   echo $K
                                         40
done
                                         60

for file in `ls /etc/*.ini`              /etc/odbc.ini
do                                       /etc/odbcinst.ini
   echo $file                            /etc/php.ini
done                                     $
                              www.opengurukul.com            59
Shell Scripting: Control Structures : case

The case construct has the following syntax:
    case word in
      pattern)
                 list of commands
                 ;;
      pattern)
                 list of commands
                 ;;
            *)
                 list of commands
                 ;;
                               www.opengurukul.com   60
    esac
Shell Scripting: Control Structures : case :
                    example

Program :                                Output :

# example : case_stmt.sh
                                         $ sh case_stmt.sh 1
rank=$1
                                         first
case $rank in
                                         $
 1)     echo "first"

        ;;                               $ sh case_stmt.sh 2
 2)     echo "second"                    second
       ;;                                $

 *)    echo "invalid input"
                                         $ sh case_stmt.sh 5
       ;;                     www.opengurukul.com              61
                                         invalid input
esac
Unix Shell Scripting




  Module : Functions




      www.opengurukul.com   62
Shell Scripting: Functions
The syntax of an Shell function is defined as follows:
name ()
{
  commands
  ...
  commands
}
A function can be used to perform task that gets repeated multiple
times in shell script.
A function will return with a default exit status of zero, one can return
different exit status' by using the notation return exit status.
Variables can be defined locally within a function using local
name=value.
                             www.opengurukul.com                            63
Shell Scripting: Functions : Example

Program :                          Output :


# example : func_sum.sh            $ sh func_sum.sh
                                   sum is : 3
sum() {                            $
result=`expr $1 + $2`
echo "sum is : " $result
}
                        www.opengurukul.com           64
Shell Scripting: Functions : Scope of
                     Variables
There is no scoping in Shell Scripts.
The scope applies only to arguments to Shell Script and arguments to
functions.
The arguments to both Shell Script and Functions are referred to as $1, $2, ...
etc.
$0 universally stores Shell Script Name.
$1
     within a function represents first argument to function.
     In a global scope (outside functions) represent first argument to Shell
        Script.
$2
     within a function represents second argument to function
     In a global scope (outside functions) represent second argument to
        Script.
                                www.opengurukul.com                            65
So on...
Shell Scripting: Functions : Scope of
             Variables : Example

Program :                              Output :


                                       $ sh scope_args.sh 100 200
# example : scope_args.sh
                                       program : $0 = scope_args.sh
                                       shell argc : $# = 2
echo 'program : $0 = ' $0
                                       shell args : $* = 100 200
echo 'shell argc : $# = ' $#           func argc : $# = 3
echo 'shell args : $* = ' $*           func args : $* = 10 20 30
                                       $
myfunc() {
                            www.opengurukul.com                       66
 echo 'func argc : $# = ' $#
Shell Scripting: Functions : List of Functions

We can get list of functions that are      Output :
available in the current context in
bash using 'declare -f'
Program :                                  $ sh func_declare.sh
$ cat func_declare.sh                      msg ()
# example : func_declare.sh                {
msg() {                                        echo "hello world"
echo "hello world"                         }
}
                                           $
declare -f
$

                                www.opengurukul.com                 67
Unix Shell Scripting




  Module : Debugging




      www.opengurukul.com   68
Shell Scripting: Debugging
-v

     The shell write its input to standard error as it is read.

-x

     The shell shall write to standard error a trace for each command
       after it expands the command and before it executes it.




                               www.opengurukul.com                      69
Shell Scripting: Debugging

For small scripts
$ sh -x script_name


For huge scripts
$ sh -x script_name > /tmp/script_out.txt 2>&1




                           www.opengurukul.com   70
Shell Scripting: Debugging : Example

Program :                        Debug :


# example : debug.sh             $ sh -v -x debug.sh

a=$1                             a=$1
                                 + a=
b=$2
                                 b=$2
c=`expr $a+$b`
   Run:                          + b=
echo $c
$ sh debug.sh
expr: syntax error               c=`expr $a+$b`
                                 expr $a+$b
$                                 ++ expr
                       www.opengurukul.com   +         71
Support


       Please register yourself
                 @
        www.opengurukul.com
In case you need any support in future.




              www.opengurukul.com         72

Mais conteúdo relacionado

Mais procurados

Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell ScriptingMustafa Qasim
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scriptingvceder
 
Bash shell
Bash shellBash shell
Bash shellxylas121
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash scriptSimon Su
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
Shell & Shell Script
Shell & Shell Script Shell & Shell Script
Shell & Shell Script Amit Ghosh
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scriptingAkshay Siwal
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Zyxware Technologies
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programmingsudhir singh yadav
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?Lloyd Huang
 
Linux shell env
Linux shell envLinux shell env
Linux shell envRahul Pola
 
BASH Guide Summary
BASH Guide SummaryBASH Guide Summary
BASH Guide SummaryOhgyun Ahn
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 

Mais procurados (20)

Scripting and the shell in LINUX
Scripting and the shell in LINUXScripting and the shell in LINUX
Scripting and the shell in LINUX
 
Chap06
Chap06Chap06
Chap06
 
Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell Scripting
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
Bash shell
Bash shellBash shell
Bash shell
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
 
Shell & Shell Script
Shell & Shell Script Shell & Shell Script
Shell & Shell Script
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programming
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
 
Linux shell env
Linux shell envLinux shell env
Linux shell env
 
BASH Guide Summary
BASH Guide SummaryBASH Guide Summary
BASH Guide Summary
 
Shell script-sec
Shell script-secShell script-sec
Shell script-sec
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 

Semelhante a OpenGurukul : Language : Shell Scripting

390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.pptmugeshmsd5
 
Unit 11 configuring the bash shell – shell script
Unit 11 configuring the bash shell – shell scriptUnit 11 configuring the bash shell – shell script
Unit 11 configuring the bash shell – shell scriptroot_fibo
 
Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Acácio Oliveira
 
Learn to Write ur first Shell script
Learn to Write ur first Shell scriptLearn to Write ur first Shell script
Learn to Write ur first Shell scriptHanan Nmr
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfHIMANKMISHRA2
 
Shell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannonShell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannonSyed Altaf
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System AdministrationJayant Dalvi
 
Shell & Shell Script
Shell & Shell ScriptShell & Shell Script
Shell & Shell ScriptAmit Ghosh
 
(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorial(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorialjayaramprabhu
 

Semelhante a OpenGurukul : Language : Shell Scripting (20)

390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
 
Unit 11 configuring the bash shell – shell script
Unit 11 configuring the bash shell – shell scriptUnit 11 configuring the bash shell – shell script
Unit 11 configuring the bash shell – shell script
 
Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Licão 09 variables and arrays v2
Licão 09 variables and arrays v2
 
Learn to Write ur first Shell script
Learn to Write ur first Shell scriptLearn to Write ur first Shell script
Learn to Write ur first Shell script
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
 
Shell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannonShell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannon
 
Shell programming
Shell programmingShell programming
Shell programming
 
Licão 05 scripts exemple
Licão 05 scripts exempleLicão 05 scripts exemple
Licão 05 scripts exemple
 
What is a shell script
What is a shell scriptWhat is a shell script
What is a shell script
 
003 scripting
003 scripting003 scripting
003 scripting
 
Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
 
Powershell notes
Powershell notesPowershell notes
Powershell notes
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
 
SHELL PROGRAMMING
SHELL PROGRAMMINGSHELL PROGRAMMING
SHELL PROGRAMMING
 
Shell & Shell Script
Shell & Shell ScriptShell & Shell Script
Shell & Shell Script
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
 
21bUc8YeDzZpE
21bUc8YeDzZpE21bUc8YeDzZpE
21bUc8YeDzZpE
 
(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorial(Ebook) linux shell scripting tutorial
(Ebook) linux shell scripting tutorial
 

Mais de Open Gurukul

Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpen Gurukul
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpen Gurukul
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : PythonOpen Gurukul
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpen Gurukul
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpen Gurukul
 

Mais de Open Gurukul (7)

Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
OpenGurukul : Operating System : Linux
OpenGurukul : Operating System : LinuxOpenGurukul : Operating System : Linux
OpenGurukul : Operating System : Linux
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

OpenGurukul : Language : Shell Scripting

  • 1. Unix Shell Scripting By OpenGurukul.com Free/Open Source Software Laboratory
  • 2. Unix Shell Scripting Module : Introduction www.opengurukul.com 2
  • 3. Introduction: Shell Program On Unix systems, shell program acts as an interface between user and operating system. The shell program is executed for a user when a user logs in by scanning /etc/passwd file (last entry has the shell program name). The most common used shell program is /bin/sh. On different flavours of unix, /bin/sh may be a symbolic link or hard link to actual scripting program. www.opengurukul.com 3
  • 4. Introduction: Shell Program The current shell program that is in use is stored in environment variable SHELL. To find the current shell program, use following command $ echo $SHELL /bin/bash $ www.opengurukul.com 4
  • 5. Introduction: Popular Shell Programs Shells which are more popular are - i) bourne again shell (bash), ii) korn shell (ksh) iii) c shell (csh). Linux uses bash (Bourne again shell) by default. AIX uses korn shell by default. There are other shells like posix shell, ksh93 etc. The shell programs that are supported on the systems are stored in the file /etc/shells on Linux. www.opengurukul.com 5
  • 6. Shell Scripting: Introduction : Shell Supported To find shells which are supported on your Linux system. $ cat /etc/shells /bin/sh /bin/bash /sbin/nologin /bin/zsh $ www.opengurukul.com 6
  • 7. Shell Scripting: Introduction : Shell Script Extension The shell scripts generally ends with an extension .sh (for korn and bourne shell). It is not mandatory to have an extension. www.opengurukul.com 7
  • 8. Shell Scripting: Introduction : Shell Script A sequence of command that we generally type on the command prompt can be placed in a file and all the commands can be executed at one shot. The file which contains commands to be interpreted by shell program is called shell script. The first line in the shell script is generally. #!/bin/sh It indicates that /bin/sh should be used to interpret the lines in the file. www.opengurukul.com 8
  • 9. Shell Scripting: Introduction : Create Shell Script Write a sequence of commands you would like to execute in a file. Ensure that the first line indicates the location of interpreter. Example : #!/bin/sh # Example : hello_world.sh echo Hello World www.opengurukul.com 9
  • 10. Shell Scripting: Introduction : Execute Permissions on the Shell Script The shell script can be made executable by using $ chmod +x script_name.sh www.opengurukul.com 10
  • 11. Shell Scripting: Introduction: Execute the Shell Script $ sh ./hello_world.sh Hello World $ www.opengurukul.com 11
  • 12. Shell Scripting: Introduction: Exit Status The exit command terminates a script. The exit command can return a value, which is available to the script's parent process. Exit status of last command is stored in $? When script ends with exit that has no parameter, exit status of the script is the exit status of the last command executed in the script. Equivalent of a bare exit is exit $? or even just omitting the exit. www.opengurukul.com 12
  • 13. Shell Scripting: Introduction: Exit Status Significance of Value of Exit Status 0 indicates successful execution. non-0 indicates failed execution. Example : Success & Failure Failure: Success: $ ls /file/does/not/exist $ ls > /dev/null $ echo $? $ echo $? 1 0 $ $ www.opengurukul.com 13
  • 14. Shell Scripting: Introduction: Comments Single Line The character "#" (hash) is used to add # Example : comments.sh single line comment in a shell script. Anything that follows # is a comment. # This is a comment. www.opengurukul.com 14
  • 15. Shell Scripting: Introduction: Comments Multple Line The multi-line comment is # Example : comment_multi.sh created in shell script using ':' : ' i am followed by a comment in single quotes. a multi line Donot forget to put a space Comment ' between : (colon) and ' (single quote). www.opengurukul.com 15
  • 16. Unix Shell Scripting Module : Variables www.opengurukul.com 16
  • 17. Shell Scripting: Variables: List To see the list of variables such as PATH, HOME etc, you can use 'env' command. $ env ... PATH=/bin:/sbin:/home/sachin/bin HOME=/home/sachin SHELL=/bin/bash ... $ www.opengurukul.com 17
  • 18. Shell Scripting: Variables : Export New variables can be instantiated using variable_name = variable_value Variables are referenced using either $variable_name or $ {variable_name}. www.opengurukul.com 18
  • 19. Shell Scripting: Variables : Export: example Example : Example : $ export A=a $ MYNAME=matsya $ echo $A123 # no output $ export MYNAME $echo ${A}123 (or) A123 $ export MYNAME=matsya $ $ echo $MYNAME www.opengurukul.com 19
  • 20. Shell Scripting : Variables : Single Quote vs Double Quote In single quote, variable values are not expanded. In double quote, variables values will expand. We can use (escape sequence) before $ to remove special meaning. www.opengurukul.com 20
  • 21. Shell Scripting : Variables : Single Quote vs Double Quote : Example #!/bin/sh # Example : quote.sh export USER=matsya1 echo without quotes : $USER # prints matsya1 echo "double quotes : $USER" # prints matsya1 echo 'single quote: $USER' # prints $USER www.opengurukul.com 21 echo "escape sequence: $USER" # prints $USER
  • 22. Shell Scripting: Variables : Data Types Shell Variables are untyped. We can use the same variable to store integer and string. Example : x=123; x="hello" www.opengurukul.com 22
  • 23. Shell Scripting: Variables: Integer Variables declare -i variable_name statement can be used to create integer variables. Program: Output: $ cat integer_variables.sh $ sh integer_variables.sh #!/bin/sh count : 10 declare -i count count : 0 count=10 $ echo "count : $count" count="hello" echo "count : $count" $ www.opengurukul.com 23
  • 24. Shell Scripting: Variables : Read-Only Variables declare -r var1 works the same as Program: readonly var1, used to create $ cat -n readonly_variable.sh read-only variable. #!/bin/sh declare -r count=10 echo $count count=20 echo $count $ Output: $ sh readonly_variable.sh 10 readonly_variable.sh: line 5: count: www.opengurukul.com 24 readonly variable
  • 25. Shell Scripting: Variables : The read command read variable_name will store the Program : value read from keyboard into variable_name # Example : read_cmd.sh echo "Enter your name " read name echo "Your name is $name" Output : $ sh read_cmd.sh Enter your name Matsya Technologies www.opengurukul.com 25 Your name is Matsya Technologies
  • 26. Shell Scripting: Variables : REPLY Variable The read command without a Program : variable name will store the value # read_cmd_reply.sh entered from keyboard into a built- in variable REPLY. echo "Enter your name" read echo "Your name is $REPLY" Output : $ sh read_cmd_reply.sh Enter your name Matsya Tech www.opengurukul.com 26
  • 27. Unix Shell Scripting Module : Program Arguments www.opengurukul.com 27
  • 28. Shell Scripting: Program Arguments Script Name $0 is special argument and it contains name of the script itself. Arguments $1 is the first argument $2 is the second argument and so on. NOTE To reference to 10th argument, we must use curly braces around it. E.g. ${10}. www.opengurukul.com 28
  • 29. Shell Scripting: Program Arguments: Special Built-in Variables $# represents the parameter count. Useful for controlling loop constructs that need to process each parameter. $@ expands to all the parameters separated by spaces. Useful for passing all the parameters to some other function or program. $$ expands to the process id of the shell that invoked the script. Useful for creating unique temporary filenames relative to this instantiation of the script. www.opengurukul.com 29
  • 30. Shell Scripting: Program Arguments: Example Program: Output : # Example : prog_arg.sh $ sh prog_arg.sh swathi matsya echo 'PID : $$ = ' $$ PID : $$ = 4531 echo 'prog name : $0 = ' $0 prog name : $0 = prog_arg.sh echo 'prog: param count : $# = ' $# prog: param count : $# = 2 echo 'prog: params : $* = ' $* prog: params : $* = swathi matsya echo 'prog: first param : $1 = ' $1 prog: first param : $1 = swathi $ www.opengurukul.com 30
  • 31. Shell Scripting: Program Arguments: $@ and $* $@ behaves like $* except that Program : when quoted the arguments are # example : d_at.sh broken up properly if there are spaces in them. for var in ”$@” do echo "$var" done : Output $ sh d_at.sh 1 2 '3 4' 1 2 34 www.opengurukul.com 31 $
  • 32. Shell Scripting: Program Arguments: $@ and $* : Example $* Program : Program : # example : d_star_quote.sh # example : d_star_noquotes.sh for var in ”$*” for var in $* do do echo "$var" echo "$var" done : Output done : Output $ sh d_star_quote.sh 1 2 '3 4' $ sh d_star_noquotes.sh 1 2 '3 4' 1234 1 $ 2 www.opengurukul.com 32 3
  • 33. Shell Scripting : Program Arguments: $@ and $* : Example # $@ in double quotes : correct way # $* in double quotes dat_dq() { dstar_dq() { echo '$@ in double quotes : ' echo '$* in double quotes : ' for var in "$@" ; do for var in "$*" ; do echo $var echo $var done done } } # $@ in no quotes www.opengurukul.com 33 dat_nq() {
  • 34. $ sh dstar_dat.sh # $@ in no quotes $@ in double quotes : dstar_nq() { 1 echo '$* without any quotes : ' 23 for var in $* ; do 4 echo $var $@ without any quotes : done 1 } 2 3 dat_dq 1 '2 3' 4 4 dat_nq 1 '2 3' 4 $* without www.opengurukul.com any quotes : 34
  • 35. Shell Scripting: Program Arguments : shift command Shift The shift command can be used to shift arguments to left side. We can specify a count and we lose that many arguments on the left side. For a shift of 1, $2 becomes $1 and so on. For a shift of 2, $3 will become $1. It is useful to process arguments in a loop using a single variable to reference to argument one by one. www.opengurukul.com 35
  • 36. Shell Scripting: Program Arguments: shift command: Example Program : Output : echo 'prog: param count : $# = ' $# echo 'prog: params : $* = ' $* $ sh prog_arg_shift.sh 10 20 30 40 prog: param count : $# = 4 shift prog: params : $* = 10 20 30 40 after shift echo "after shift" prog: param count : $# = 3 echo 'prog: param count : $# = ' $# prog: params : $* = 20 30 40 echo 'prog: params : $* = ' $* after shift 2 prog: param count : $# = 1 shift 2 www.opengurukul.com params prog: : $* = 40 36
  • 37. Unix Shell Scripting Module : Misc www.opengurukul.com 37
  • 38. Shell Scripting: Misc : Command Substitution In a shell script, the output of a command can be substituted in place of command name using following syntax. $(command) `command` Such command will be executed in a sub-shell. The standard output from sub shell will be used in the place of command when the command completes. www.opengurukul.com 38
  • 39. Shell Scripting: Misc : Command Substitution : Example Program : Output : # example : cmd_subst.sh $ sh cmd_subst.sh 10 20 a=$1 sum : 30 b=$2 sum : 30 $ total=$(expr $a + $b) echo "sum : $total" total=`expr $a + $b` echo "sum : $total" www.opengurukul.com 39
  • 40. Shell Scripting: Misc : Arithmetic Expansion Arithmetic expansion is also allowed and comes in the form: $((expression)) The value of the expression will replace the substitution. Example : will echo "8" to stdout. #!/bin/sh echo $((1+3+4)) www.opengurukul.com 40
  • 41. Shell Scripting: Misc : Arithmetic Expansion : Example Program : Output : # example : arith_expr.sh $ sh ./arith_expr.sh 40 50 x=$1 90 y=$2 90 90 echo $(expr $x + $y) $ echo $(($x + $y)) www.opengurukul.com 41
  • 42. Unix Shell Scripting Module : Test Command www.opengurukul.com 42
  • 43. Shell Scripting: Test Command The test command or [ expression ] is used to check if an expression is true. If it is true, 0(zero) is returned otherwise non-zero is returned. $ test 1 -eq 1 # test equal to $ echo $? 0 $ $ test 1 -eq 10 # test not equal to $ echo $? 1 $ www.opengurukul.com 43
  • 44. Shell Scripting: Test Command : Example Program : Output : # example : test_cmd.sh $ sh test_cmd.sh if test 1 -eq 1 ; then test succeeded echo "test succeeded"; $ fi www.opengurukul.com 44
  • 45. Shell Scripting: Test Command: Numbers Use test command to compare numbers Numeric Test Operators -eq = equal to -ne = not equal to -lt = less than -le = less than or equal to -gt = greater than www.opengurukul.com 45
  • 46. Shell Scripting: Test Command: Numbers Program : Output : a1=$1 op=$2 $ sh test_cmd_num.sh 50 -eq 60 a2=$3 if test ${a1} $op ${a2}; then false echo "true" else false echo "false" fi $ sh test_cmd_num.sh 50 -eq 50 if [ ${a1} $op ${a2} ]; then echo "true" true else echo "false" true fi www.opengurukul.com 46
  • 47. Shell Scripting: Test Command: Strings String Tests Equality s1 = s2 Inequality s1 != s2 Zero (Length is zero) -z str Non-zero (Length is non-zero) -n str www.opengurukul.com 47
  • 48. Shell Scripting: Test Command: Strings Program : Output : # example : test_cmd_str.sh $ sh test_cmd_str.sh in = in x=$1 op=$2 true y=$3 $ if [ $x $op $y ]; then $ sh test_cmd_str.sh in != out echo "true" true else echo "false" $ fi $ sh test_cmd_str.sh www.opengurukul.com in != in 48
  • 49. Shell Scripting: Test Command : Files The test command can also be used to figure out the file type. File Exists -e file Normal File (Not a directory) -f file Directory -d file Symbolic Link -h file Pipe -p file Character Device File -c file Block Device File -b file Socket File -S file Writable -w file Readable -r file Executable -x file Non-Empty file -s file www.opengurukul.com 49
  • 50. Shell Scripting: Test Command : Files : Example Program : Output : # example : test_cmd_file.sh file=$1 $ sh test_cmd_file.sh /bin/bash if [ -d $file ] ; then /bin/bash is a regular file echo "$file is a directory" $ elif [ -f $file ] ; then echo "$file is a regular file" else $ sh test_cmd_file.sh /home echo "$file type not known"; /home is a directory fi $ www.opengurukul.com 50
  • 51. Shell Scripting: Test Command : Logical Operators NOT ! expr AND expr1 -a expr2 OR expr1 -o expr2 www.opengurukul.com 51
  • 52. Shell Scripting: Test Command : Logical Operators : Example Program: Output : # example: test_cmd_logical.sh $ sh test_cmd_logical.sh 5 4 3 5 is biggest x=$1 $ y=$2 z=$3 # if test $x -lt $y if [ $x -gt $y -a $x -gt $z ];www.opengurukul.com then 52
  • 53. Unix Shell Scripting Module : Control Structures www.opengurukul.com 53
  • 54. Shell Scripting: Control Structures : if construct The format of if else fi is. if test condition1 then List of commands1 elif test condition2 then List of commands2 elif test condition3 then List of commands3 www.opengurukul.com 54 else
  • 55. Shell Scripting: Control Structures : if example Program : Output : # example : if_construct.sh $ sh if_construct.sh /var /var: found file=$1 $ if [ -e $file ] then $ sh if_construct.sh /not echo "$file: found" /not: not found else $ www.opengurukul.com 55 echo "$file: not found"
  • 56. Shell Scripting: Control Structures: while The While...Do has the following generic form: while test condtion do series of commands done www.opengurukul.com 56
  • 57. Shell Scripting: Control Structures: while : example Program : Output : # example : while_construct.sh K=$1 $ sh while_construct.sh 5 9 LIMIT=$2 5 6 while test $K -le $LIMIT 7 do 8 echo "$K" K=$(( K + 1 )) 9 done $ www.opengurukul.com 57
  • 58. Shell Scripting: Control Structures: for The syntax of the for command is: for variable in list of values do list of commands done www.opengurukul.com 58
  • 59. Shell Scripting: Control Structures: for : Example Program : Output : # example : for_loop.sh for K in 20 40 60 $ sh for_loop.sh do 20 echo $K 40 done 60 for file in `ls /etc/*.ini` /etc/odbc.ini do /etc/odbcinst.ini echo $file /etc/php.ini done $ www.opengurukul.com 59
  • 60. Shell Scripting: Control Structures : case The case construct has the following syntax: case word in pattern) list of commands ;; pattern) list of commands ;; *) list of commands ;; www.opengurukul.com 60 esac
  • 61. Shell Scripting: Control Structures : case : example Program : Output : # example : case_stmt.sh $ sh case_stmt.sh 1 rank=$1 first case $rank in $ 1) echo "first" ;; $ sh case_stmt.sh 2 2) echo "second" second ;; $ *) echo "invalid input" $ sh case_stmt.sh 5 ;; www.opengurukul.com 61 invalid input esac
  • 62. Unix Shell Scripting Module : Functions www.opengurukul.com 62
  • 63. Shell Scripting: Functions The syntax of an Shell function is defined as follows: name () { commands ... commands } A function can be used to perform task that gets repeated multiple times in shell script. A function will return with a default exit status of zero, one can return different exit status' by using the notation return exit status. Variables can be defined locally within a function using local name=value. www.opengurukul.com 63
  • 64. Shell Scripting: Functions : Example Program : Output : # example : func_sum.sh $ sh func_sum.sh sum is : 3 sum() { $ result=`expr $1 + $2` echo "sum is : " $result } www.opengurukul.com 64
  • 65. Shell Scripting: Functions : Scope of Variables There is no scoping in Shell Scripts. The scope applies only to arguments to Shell Script and arguments to functions. The arguments to both Shell Script and Functions are referred to as $1, $2, ... etc. $0 universally stores Shell Script Name. $1 within a function represents first argument to function. In a global scope (outside functions) represent first argument to Shell Script. $2 within a function represents second argument to function In a global scope (outside functions) represent second argument to Script. www.opengurukul.com 65 So on...
  • 66. Shell Scripting: Functions : Scope of Variables : Example Program : Output : $ sh scope_args.sh 100 200 # example : scope_args.sh program : $0 = scope_args.sh shell argc : $# = 2 echo 'program : $0 = ' $0 shell args : $* = 100 200 echo 'shell argc : $# = ' $# func argc : $# = 3 echo 'shell args : $* = ' $* func args : $* = 10 20 30 $ myfunc() { www.opengurukul.com 66 echo 'func argc : $# = ' $#
  • 67. Shell Scripting: Functions : List of Functions We can get list of functions that are Output : available in the current context in bash using 'declare -f' Program : $ sh func_declare.sh $ cat func_declare.sh msg () # example : func_declare.sh { msg() { echo "hello world" echo "hello world" } } $ declare -f $ www.opengurukul.com 67
  • 68. Unix Shell Scripting Module : Debugging www.opengurukul.com 68
  • 69. Shell Scripting: Debugging -v The shell write its input to standard error as it is read. -x The shell shall write to standard error a trace for each command after it expands the command and before it executes it. www.opengurukul.com 69
  • 70. Shell Scripting: Debugging For small scripts $ sh -x script_name For huge scripts $ sh -x script_name > /tmp/script_out.txt 2>&1 www.opengurukul.com 70
  • 71. Shell Scripting: Debugging : Example Program : Debug : # example : debug.sh $ sh -v -x debug.sh a=$1 a=$1 + a= b=$2 b=$2 c=`expr $a+$b` Run: + b= echo $c $ sh debug.sh expr: syntax error c=`expr $a+$b` expr $a+$b $ ++ expr www.opengurukul.com + 71
  • 72. Support Please register yourself @ www.opengurukul.com In case you need any support in future. www.opengurukul.com 72