Unix Shell Scripting                By         OpenGurukul.comFree/Open Source Software Laboratory
Unix Shell Scripting Module : Introduction      www.opengurukul.com   2
Introduction: Shell ProgramOn Unix systems, shell program acts as an interface between userand operating system.The shell ...
Introduction: Shell ProgramThe current shell program that is in use is stored in environmentvariable SHELL.To find the cur...
Introduction: Popular Shell ProgramsShells which are more popular are -i) bourne again shell (bash),ii) korn shell (ksh)ii...
Shell Scripting: Introduction : Shell                   SupportedTo find shells which are supported on your Linux system. ...
Shell Scripting: Introduction : Shell Script                  ExtensionThe shell scripts generally ends with an extension ...
Shell Scripting: Introduction : Shell ScriptA sequence of command that we generally type on thecommand prompt can be place...
Shell Scripting: Introduction : Create Shell                    ScriptWrite a sequence of commands you would like to execu...
Shell Scripting: Introduction : Execute       Permissions on the Shell ScriptThe shell script can be made executable by us...
Shell Scripting: Introduction: Execute the                   Shell Script$ sh ./hello_world.shHello World$                ...
Shell Scripting: Introduction: Exit StatusThe exit command terminates a script.The exit command can return a value, which ...
Shell Scripting: Introduction: Exit StatusSignificance of Value of Exit Status      0 indicates successful execution.     ...
Shell Scripting: Introduction: Comments                   Single LineThe character "#" (hash) is used to add     # Example...
Shell Scripting: Introduction: Comments                  Multple LineThe multi-line comment is              # Example : co...
Unix Shell Scripting  Module : Variables      www.opengurukul.com   16
Shell Scripting: Variables: ListTo see the list of variables such as PATH, HOME etc, you can useenv command.$ env...PATH=/...
Shell Scripting: Variables : ExportNew variables can be instantiated usingvariable_name = variable_valueVariables are refe...
Shell Scripting: Variables : Export: exampleExample :                           Example :                                 ...
Shell Scripting : Variables : Single      Quote vs Double QuoteIn single quote, variable values are not expanded.In double...
Shell Scripting : Variables : SingleQuote vs Double Quote : Example#!/bin/sh# Example : quote.shexport USER=matsya1echo wi...
Shell Scripting: Variables : Data TypesShell Variables are untyped.We can use the same variable to store integer and strin...
Shell Scripting: Variables: Integer Variablesdeclare -i variable_name statement can be used to create integervariables.Pro...
Shell Scripting: Variables : Read-Only                    Variablesdeclare -r var1 works the same as Program:readonly var1...
Shell Scripting: Variables : The read                    commandread variable_name will store the      Program :value read...
Shell Scripting: Variables : REPLY VariableThe read command without a              Program :variable name will store the v...
Unix Shell ScriptingModule : Program Arguments        www.opengurukul.com   27
Shell Scripting: Program ArgumentsScript Name $0 is special argument and it contains name of the script itself.Arguments$1...
Shell Scripting: Program Arguments: Special              Built-in Variables$# represents the parameter count.   Useful for...
Shell Scripting: Program             Arguments: ExampleProgram:                                    Output :# Example : pro...
Shell Scripting: Program           Arguments: $@ and $*$@ behaves like $* except that         Program :  when quoted the a...
Shell Scripting: ProgramArguments: $@ and $* : Example $*Program :                                   Program :# example : ...
Shell Scripting : Program Arguments:        $@ and $* : Example# $@ in double quotes : correct way        # $* in double q...
$ sh dstar_dat.sh# $@ in no quotes                           $@ in double quotes :dstar_nq() {                            ...
Shell Scripting: Program Arguments : shift                  commandShiftThe shift command can be used to shift arguments t...
Shell Scripting: Program          Arguments: shift command:                   ExampleProgram :                            ...
Unix Shell Scripting    Module : Misc      www.opengurukul.com   37
Shell Scripting: Misc : Command                    SubstitutionIn a shell script, the output of a command can be substitut...
Shell Scripting: Misc : Command              Substitution : ExampleProgram :                             Output :# example...
Shell Scripting: Misc : Arithmetic ExpansionArithmetic expansion is also allowed and comes in the form:$((expression))The ...
Shell Scripting: Misc : Arithmetic             Expansion : ExampleProgram :                              Output :# example...
Unix Shell ScriptingModule : Test Command      www.opengurukul.com   42
Shell Scripting: Test CommandThe test command or [ expression ] is used to check if an expression is true. If it istrue, 0...
Shell Scripting: Test Command : ExampleProgram :                                Output :# example : test_cmd.sh           ...
Shell Scripting: Test Command: NumbersUse test command to compare numbersNumeric Test Operators-eq = equal to-ne = not equ...
Shell Scripting: Test Command: NumbersProgram :                                  Output :a1=$1op=$2                       ...
Shell Scripting: Test Command: StringsString TestsEquality                            s1 = s2Inequality                   ...
Shell Scripting: Test Command: StringsProgram :                              Output :# example : test_cmd_str.sh          ...
Shell Scripting: Test Command : FilesThe test command can also be used to figure out the file type.File Exists            ...
Shell Scripting: Test Command : Files :                    ExampleProgram :                            Output :# example :...
Shell Scripting: Test Command : Logical                 OperatorsNOT    ! exprAND    expr1 -a expr2OR     expr1 -o expr2  ...
Shell Scripting: Test Command : Logical             Operators : ExampleProgram:                                  Output :#...
Unix Shell ScriptingModule : Control Structures        www.opengurukul.com   53
Shell Scripting: Control Structures : if                     constructThe format of if else fi is.if test condition1then  ...
Shell Scripting: Control Structures : if                      exampleProgram :                             Output :# examp...
Shell Scripting: Control Structures: whileThe While...Do has the following generic form:while test condtiondo  series of c...
Shell Scripting: Control Structures: while :                   exampleProgram :                             Output :# exam...
Shell Scripting: Control Structures: forThe syntax of the for command is:for variable in list of valuesdo     list of comm...
Shell Scripting: Control Structures: for :                     ExampleProgram :                                Output :# e...
Shell Scripting: Control Structures : caseThe case construct has the following syntax:    case word in      pattern)      ...
Shell Scripting: Control Structures : case :                    exampleProgram :                                Output :# ...
Unix Shell Scripting  Module : Functions      www.opengurukul.com   62
Shell Scripting: FunctionsThe syntax of an Shell function is defined as follows:name (){  commands  ...  commands}A functi...
Shell Scripting: Functions : ExampleProgram :                          Output :# example : func_sum.sh            $ sh fun...
Shell Scripting: Functions : Scope of                     VariablesThere is no scoping in Shell Scripts.The scope applies ...
Shell Scripting: Functions : Scope of             Variables : ExampleProgram :                              Output :      ...
Shell Scripting: Functions : List of FunctionsWe can get list of functions that are      Output :available in the current ...
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...
Shell Scripting: DebuggingFor small scripts$ sh -x script_nameFor huge scripts$ sh -x script_name > /tmp/script_out.txt 2>...
Shell Scripting: Debugging : ExampleProgram :                        Debug :# example : debug.sh             $ sh -v -x de...
Support       Please register yourself                 @        www.opengurukul.comIn case you need any support in future....
Upcoming SlideShare
Loading in...5
×

OpenGurukul : Language : Shell Scripting

2,163

Published on

Shell Scripting by OpenGurukul

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,163
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "OpenGurukul : Language : Shell Scripting"

  1. 1. Unix Shell Scripting By OpenGurukul.comFree/Open Source Software Laboratory
  2. 2. Unix Shell Scripting Module : Introduction www.opengurukul.com 2
  3. 3. Introduction: Shell ProgramOn Unix systems, shell program acts as an interface between userand operating system.The shell program is executed for a user when a user logs in byscanning /etc/passwd file (last entry has the shell programname).The most common used shell program is /bin/sh. On differentflavours of unix, /bin/sh may be a symbolic link or hard link toactual scripting program. www.opengurukul.com 3
  4. 4. Introduction: Shell ProgramThe current shell program that is in use is stored in environmentvariable SHELL.To find the current shell program, use following command$ echo $SHELL/bin/bash$ www.opengurukul.com 4
  5. 5. Introduction: Popular Shell ProgramsShells 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 arestored in the file /etc/shells on Linux. www.opengurukul.com 5
  6. 6. Shell Scripting: Introduction : Shell SupportedTo 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. 7. Shell Scripting: Introduction : Shell Script ExtensionThe 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. 8. Shell Scripting: Introduction : Shell ScriptA sequence of command that we generally type on thecommand prompt can be placed in a file and all the commandscan be executed at one shot.The file which contains commands to be interpreted by shellprogram is called shell script.The first line in the shell script is generally.#!/bin/shIt indicates that /bin/sh should be used to interpret the lines inthe file. www.opengurukul.com 8
  9. 9. Shell Scripting: Introduction : Create Shell ScriptWrite a sequence of commands you would like to executein a file.Ensure that the first line indicates the location of interpreter.Example :#!/bin/sh# Example : hello_world.shecho Hello World www.opengurukul.com 9
  10. 10. Shell Scripting: Introduction : Execute Permissions on the Shell ScriptThe shell script can be made executable by using$ chmod +x script_name.sh www.opengurukul.com 10
  11. 11. Shell Scripting: Introduction: Execute the Shell Script$ sh ./hello_world.shHello World$ www.opengurukul.com 11
  12. 12. Shell Scripting: Introduction: Exit StatusThe exit command terminates a script.The exit command can return a value, which is available tothe scripts parent process.Exit status of last command is stored in $?When script ends with exit that has no parameter, exitstatus of the script is the exit status of the last commandexecuted in the script.Equivalent of a bare exit is exit $? or even just omitting theexit. www.opengurukul.com 12
  13. 13. Shell Scripting: Introduction: Exit StatusSignificance of Value of Exit Status 0 indicates successful execution. non-0 indicates failed execution.Example : Success & FailureFailure: Success:$ ls /file/does/not/exist $ ls > /dev/null$ echo $? $ echo $?1 0$ $ www.opengurukul.com 13
  14. 14. Shell Scripting: Introduction: Comments Single LineThe character "#" (hash) is used to add # Example : comments.shsingle line comment in a shell script.Anything that follows # is a comment. # This is a comment. www.opengurukul.com 14
  15. 15. Shell Scripting: Introduction: Comments Multple LineThe multi-line comment is # Example : comment_multi.shcreated in shell script using : : i amfollowed by a comment insingle quotes. a multi lineDonot forget to put a space Comment between : (colon) and (singlequote). www.opengurukul.com 15
  16. 16. Unix Shell Scripting Module : Variables www.opengurukul.com 16
  17. 17. Shell Scripting: Variables: ListTo see the list of variables such as PATH, HOME etc, you can useenv command.$ env...PATH=/bin:/sbin:/home/sachin/binHOME=/home/sachinSHELL=/bin/bash...$ www.opengurukul.com 17
  18. 18. Shell Scripting: Variables : ExportNew variables can be instantiated usingvariable_name = variable_valueVariables are referenced using either $variable_name or ${variable_name}. www.opengurukul.com 18
  19. 19. Shell Scripting: Variables : Export: exampleExample : 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. 20. Shell Scripting : Variables : Single Quote vs Double QuoteIn 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. 21. Shell Scripting : Variables : SingleQuote vs Double Quote : Example#!/bin/sh# Example : quote.shexport USER=matsya1echo without quotes : $USER # prints matsya1echo "double quotes : $USER" # prints matsya1echo single quote: $USER # prints $USER www.opengurukul.com 21echo "escape sequence: $USER" # prints $USER
  22. 22. Shell Scripting: Variables : Data TypesShell Variables are untyped.We can use the same variable to store integer and string.Example : x=123; x="hello" www.opengurukul.com 22
  23. 23. Shell Scripting: Variables: Integer Variablesdeclare -i variable_name statement can be used to create integervariables.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. 24. Shell Scripting: Variables : Read-Only Variablesdeclare -r var1 works the same as Program:readonly var1, used to create $ cat -n readonly_variable.shread-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. 25. Shell Scripting: Variables : The read commandread variable_name will store the Program :value read from keyboard intovariable_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. 26. Shell Scripting: Variables : REPLY VariableThe read command without a Program :variable name will store the value # read_cmd_reply.shentered 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. 27. Unix Shell ScriptingModule : Program Arguments www.opengurukul.com 27
  28. 28. Shell Scripting: Program ArgumentsScript 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.NOTETo reference to 10th argument, we must use curly bracesaround it.E.g. ${10}. www.opengurukul.com 28
  29. 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. 30. Shell Scripting: Program Arguments: ExampleProgram: Output :# Example : prog_arg.sh $ sh prog_arg.sh swathi matsyaecho PID : $$ = $$ PID : $$ = 4531echo prog name : $0 = $0 prog name : $0 = prog_arg.shecho prog: param count : $# = $# prog: param count : $# = 2echo prog: params : $* = $* prog: params : $* = swathi matsyaecho prog: first param : $1 = $1 prog: first param : $1 = swathi $ www.opengurukul.com 30
  31. 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. 32. Shell Scripting: ProgramArguments: $@ and $* : Example $*Program : Program :# example : d_star_quote.sh # example : d_star_noquotes.shfor 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 41234 1$ 2 www.opengurukul.com 32 3
  33. 33. Shell Scripting : Program Arguments: $@ and $* : Example# $@ in double quotes : correct way # $* in double quotesdat_dq() { dstar_dq() {echo $@ in double quotes : echo $* in double quotes : for var in "$@" ; do for var in "$*" ; do echo $var echo $vardone done} }# $@ in no quotes www.opengurukul.com 33dat_nq() {
  34. 34. $ sh dstar_dat.sh# $@ in no quotes $@ in double quotes :dstar_nq() { 1echo $* without any quotes : 23for var in $* ; do 4 echo $var $@ without any quotes :done 1} 2 3dat_dq 1 2 3 4 4dat_nq 1 2 3 4 $* without www.opengurukul.com any quotes : 34
  35. 35. Shell Scripting: Program Arguments : shift commandShiftThe shift command can be used to shift arguments to left side.We can specify a count and we lose that many arguments on the leftside. 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 toreference to argument one by one. www.opengurukul.com 35
  36. 36. Shell Scripting: Program Arguments: shift command: ExampleProgram : Output :echo prog: param count : $# = $#echo prog: params : $* = $* $ sh prog_arg_shift.sh 10 20 30 40 prog: param count : $# = 4shift prog: params : $* = 10 20 30 40 after shiftecho "after shift" prog: param count : $# = 3echo prog: param count : $# = $# prog: params : $* = 20 30 40echo prog: params : $* = $* after shift 2 prog: param count : $# = 1shift 2 www.opengurukul.com params prog: : $* = 40 36
  37. 37. Unix Shell Scripting Module : Misc www.opengurukul.com 37
  38. 38. Shell Scripting: Misc : Command SubstitutionIn a shell script, the output of a command can be substituted in placeof 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 ofcommand when the command completes. www.opengurukul.com 38
  39. 39. Shell Scripting: Misc : Command Substitution : ExampleProgram : Output :# example : cmd_subst.sh $ sh cmd_subst.sh 10 20a=$1 sum : 30b=$2 sum : 30 $total=$(expr $a + $b)echo "sum : $total"total=`expr $a + $b`echo "sum : $total" www.opengurukul.com 39
  40. 40. Shell Scripting: Misc : Arithmetic ExpansionArithmetic 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/shecho $((1+3+4)) www.opengurukul.com 40
  41. 41. Shell Scripting: Misc : Arithmetic Expansion : ExampleProgram : Output :# example : arith_expr.sh $ sh ./arith_expr.sh 40 50x=$1 90y=$2 90 90echo $(expr $x + $y) $echo $(($x + $y)) www.opengurukul.com 41
  42. 42. Unix Shell ScriptingModule : Test Command www.opengurukul.com 42
  43. 43. Shell Scripting: Test CommandThe test command or [ expression ] is used to check if an expression is true. If it istrue, 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. 44. Shell Scripting: Test Command : ExampleProgram : Output :# example : test_cmd.sh $ sh test_cmd.shif test 1 -eq 1 ; then test succeeded echo "test succeeded"; $fi www.opengurukul.com 44
  45. 45. Shell Scripting: Test Command: NumbersUse test command to compare numbersNumeric 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. 46. Shell Scripting: Test Command: NumbersProgram : Output :a1=$1op=$2 $ sh test_cmd_num.sh 50 -eq 60a2=$3if test ${a1} $op ${a2}; then false echo "true"else false echo "false"fi $ sh test_cmd_num.sh 50 -eq 50if [ ${a1} $op ${a2} ]; then echo "true" trueelse echo "false" truefi www.opengurukul.com 46
  47. 47. Shell Scripting: Test Command: StringsString TestsEquality s1 = s2Inequality s1 != s2Zero (Length is zero) -z strNon-zero (Length is non-zero) -n str www.opengurukul.com 47
  48. 48. Shell Scripting: Test Command: StringsProgram : Output :# example : test_cmd_str.sh $ sh test_cmd_str.sh in = inx=$1op=$2 truey=$3 $if [ $x $op $y ]; then $ sh test_cmd_str.sh in != out echo "true" trueelse echo "false" $fi $ sh test_cmd_str.sh www.opengurukul.com in != in 48
  49. 49. Shell Scripting: Test Command : FilesThe test command can also be used to figure out the file type.File Exists -e fileNormal File (Not a directory) -f fileDirectory -d fileSymbolic Link -h filePipe -p fileCharacter Device File -c fileBlock Device File -b fileSocket File -S fileWritable -w fileReadable -r fileExecutable -x fileNon-Empty file -s file www.opengurukul.com 49
  50. 50. Shell Scripting: Test Command : Files : ExampleProgram : Output :# example : test_cmd_file.shfile=$1 $ sh test_cmd_file.sh /bin/bashif [ -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 directoryfi $ www.opengurukul.com 50
  51. 51. Shell Scripting: Test Command : Logical OperatorsNOT ! exprAND expr1 -a expr2OR expr1 -o expr2 www.opengurukul.com 51
  52. 52. Shell Scripting: Test Command : Logical Operators : ExampleProgram: Output :# example: test_cmd_logical.sh $ sh test_cmd_logical.sh 5 4 3 5 is biggestx=$1 $y=$2z=$3# if test $x -lt $yif [ $x -gt $y -a $x -gt $z ];www.opengurukul.com then 52
  53. 53. Unix Shell ScriptingModule : Control Structures www.opengurukul.com 53
  54. 54. Shell Scripting: Control Structures : if constructThe format of if else fi is.if test condition1then List of commands1elif test condition2then List of commands2elif test condition3then List of commands3 www.opengurukul.com 54else
  55. 55. Shell Scripting: Control Structures : if exampleProgram : Output :# example : if_construct.sh $ sh if_construct.sh /var /var: foundfile=$1 $if [ -e $file ]then $ sh if_construct.sh /not echo "$file: found" /not: not foundelse $ www.opengurukul.com 55 echo "$file: not found"
  56. 56. Shell Scripting: Control Structures: whileThe While...Do has the following generic form:while test condtiondo series of commandsdone www.opengurukul.com 56
  57. 57. Shell Scripting: Control Structures: while : exampleProgram : Output :# example : while_construct.shK=$1 $ sh while_construct.sh 5 9LIMIT=$2 5 6while test $K -le $LIMIT 7do 8 echo "$K" K=$(( K + 1 )) 9done $ www.opengurukul.com 57
  58. 58. Shell Scripting: Control Structures: forThe syntax of the for command is:for variable in list of valuesdo list of commandsdone www.opengurukul.com 58
  59. 59. Shell Scripting: Control Structures: for : ExampleProgram : Output :# example : for_loop.shfor K in 20 40 60 $ sh for_loop.shdo 20 echo $K 40done 60for file in `ls /etc/*.ini` /etc/odbc.inido /etc/odbcinst.ini echo $file /etc/php.inidone $ www.opengurukul.com 59
  60. 60. Shell Scripting: Control Structures : caseThe 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. 61. Shell Scripting: Control Structures : case : exampleProgram : Output :# example : case_stmt.sh $ sh case_stmt.sh 1rank=$1 firstcase $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 inputesac
  62. 62. Unix Shell Scripting Module : Functions www.opengurukul.com 62
  63. 63. Shell Scripting: FunctionsThe syntax of an Shell function is defined as follows:name (){ commands ... commands}A function can be used to perform task that gets repeated multipletimes in shell script.A function will return with a default exit status of zero, one can returndifferent exit status by using the notation return exit status.Variables can be defined locally within a function using localname=value. www.opengurukul.com 63
  64. 64. Shell Scripting: Functions : ExampleProgram : Output :# example : func_sum.sh $ sh func_sum.sh sum is : 3sum() { $result=`expr $1 + $2`echo "sum is : " $result} www.opengurukul.com 64
  65. 65. Shell Scripting: Functions : Scope of VariablesThere is no scoping in Shell Scripts.The scope applies only to arguments to Shell Script and arguments tofunctions.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 65So on...
  66. 66. Shell Scripting: Functions : Scope of Variables : ExampleProgram : Output : $ sh scope_args.sh 100 200# example : scope_args.sh program : $0 = scope_args.sh shell argc : $# = 2echo program : $0 = $0 shell args : $* = 100 200echo shell argc : $# = $# func argc : $# = 3echo shell args : $* = $* func args : $* = 10 20 30 $myfunc() { www.opengurukul.com 66 echo func argc : $# = $#
  67. 67. Shell Scripting: Functions : List of FunctionsWe can get list of functions that are Output :available in the current context inbash using declare -fProgram : $ 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. 68. Unix Shell Scripting Module : Debugging www.opengurukul.com 68
  69. 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. 70. Shell Scripting: DebuggingFor small scripts$ sh -x script_nameFor huge scripts$ sh -x script_name > /tmp/script_out.txt 2>&1 www.opengurukul.com 70
  71. 71. Shell Scripting: Debugging : ExampleProgram : Debug :# example : debug.sh $ sh -v -x debug.sha=$1 a=$1 + a=b=$2 b=$2c=`expr $a+$b` Run: + b=echo $c$ sh debug.shexpr: syntax error c=`expr $a+$b` expr $a+$b$ ++ expr www.opengurukul.com + 71
  72. 72. Support Please register yourself @ www.opengurukul.comIn case you need any support in future. www.opengurukul.com 72

×