• Save
OpenGurukul : Language : Shell Scripting
Upcoming SlideShare
Loading in...5
×
 

OpenGurukul : Language : Shell Scripting

on

  • 1,880 views

Shell Scripting by OpenGurukul

Shell Scripting by OpenGurukul

Statistics

Views

Total Views
1,880
Views on SlideShare
1,811
Embed Views
69

Actions

Likes
2
Downloads
0
Comments
0

1 Embed 69

http://www.opengurukul.com 69

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

OpenGurukul : Language : Shell Scripting OpenGurukul : Language : Shell Scripting Presentation Transcript

  • 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 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Shell Scripting: Introduction: Execute the Shell Script$ sh ./hello_world.shHello World$ www.opengurukul.com 11
  • 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
  • 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
  • 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
  • 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
  • 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=/bin:/sbin:/home/sachin/binHOME=/home/sachinSHELL=/bin/bash...$ www.opengurukul.com 17
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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 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
  • 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: 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
  • 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: 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
  • 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() {
  • $ 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
  • 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
  • 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
  • Unix Shell Scripting Module : Misc www.opengurukul.com 37
  • 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
  • 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
  • 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
  • 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
  • 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(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 : 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Shell Scripting: Test Command : Logical OperatorsNOT ! exprAND expr1 -a expr2OR expr1 -o expr2 www.opengurukul.com 51
  • 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
  • Unix Shell ScriptingModule : Control Structures www.opengurukul.com 53
  • 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
  • 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"
  • Shell Scripting: Control Structures: whileThe While...Do has the following generic form:while test condtiondo series of commandsdone www.opengurukul.com 56
  • 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
  • Shell Scripting: Control Structures: forThe syntax of the for command is:for variable in list of valuesdo list of commandsdone www.opengurukul.com 58
  • 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
  • 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
  • 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
  • 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 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
  • 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
  • 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...
  • 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 : $# = $#
  • 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
  • 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: DebuggingFor small scripts$ sh -x script_nameFor huge scripts$ sh -x script_name > /tmp/script_out.txt 2>&1 www.opengurukul.com 70
  • 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
  • Support Please register yourself @ www.opengurukul.comIn case you need any support in future. www.opengurukul.com 72