Upload
lynette-stokes
View
245
Download
3
Embed Size (px)
Citation preview
Lecture 4Lecture 4
C Shell Scripts(Chapter 10)C Shell Scripts(Chapter 10)
Shell script/programShell script/program
Shell script: a series of shell commands Shell script: a series of shell commands placed in an ASCII text fileplaced in an ASCII text file
Commands includeCommands include Anything you can type on the command lineAnything you can type on the command line Variables (including shell vars, env vars, Variables (including shell vars, env vars,
command args…) and Expressionscommand args…) and Expressions Control statements (if, while, for)Control statements (if, while, for)
Script executionScript execution
Two ways to run a shell script:Two ways to run a shell script: Launch a subshell with the script name as the Launch a subshell with the script name as the
argument. e.g. % cshargument. e.g. % csh my_script.sh my_script.sh Specify which shell to use within the scriptSpecify which shell to use within the script
• First line of script is as First line of script is as #!/usr/bin/csh#!/usr/bin/csh #!/usr/bin/csh –f to not read in .cshrc#!/usr/bin/csh –f to not read in .cshrc
• Make the script executable using Make the script executable using chmodchmod• Make sure the PATH includes the current directoryMake sure the PATH includes the current directory• Run directly from the command lineRun directly from the command line
Shell Script ExampleShell Script Example
file ./hello.sh:file ./hello.sh:
#!/usr/bin/csh -f#!/usr/bin/csh -f
echo Hello Worldecho Hello World
% chmod +x ./hello.sh% chmod +x ./hello.sh
% ./hello.sh% ./hello.sh
ExpressionsExpressions
C Shell expressions are used with @ or with C Shell expressions are used with @ or with (if/while) statements, where variable can be(if/while) statements, where variable can be
Expression are formed by variables + operatorsExpression are formed by variables + operators @ operator: assigns the value of arithmetic @ operator: assigns the value of arithmetic
expressions to a variableexpressions to a variable Example of @:Example of @:
% set n=2% set n=2% @ a=$n + 2% @ a=$n + 2% @ a* = 2% @ a* = 2
Spaces must surround operators!Spaces must surround operators!
OperatorsOperators Arithmetic operatorsArithmetic operators Assignment Operators ( =, +=, -=…)Assignment Operators ( =, +=, -=…) Comparison Operators (==, !=, <=…)Comparison Operators (==, !=, <=…) Bitwise and logic operators (!, &&, ||), (>>, <<)Bitwise and logic operators (!, &&, ||), (>>, <<) Pattern matching (=~, !~)Pattern matching (=~, !~)
File test operators (operator + File test operators (operator + filename)filename)
-d file: the file is a dir?-d file: the file is a dir? -e file: the file exists?-e file: the file exists? -f file: the file is a plain file?-f file: the file is a plain file? -o file: the user owns the file-o file: the user owns the file -r/w/x file: the user has read/write/execute -r/w/x file: the user has read/write/execute
permissionpermission -z file: the file has 0 size-z file: the file has 0 size ! + any above: reverse the meaning! + any above: reverse the meaning
Control StatementsControl Statements if… then…[else…]endifif… then…[else…]endifif (if (condition)condition)thenthenstatementsstatements
elseelsestatementsstatements
endifendif While…endWhile…end
Syntax:Syntax:while (while (condition)condition)statementsstatements
endend foreach...endforeach...endforeach foreach varvar ( (list)list)
statementsstatementsendend
Parameter Passing Review
Positional Parameters $0 – the currently executing script $n – the nth parameter $# -- the number of parameters
Argument Array $argv[n] – the nth parameter (n > 0) $#argv – the size of argv
Example 1Example 1
Task: Write a script that lists all its Task: Write a script that lists all its command line arguments prepended by command line arguments prepended by arguments positional indexarguments positional index
Ex:Ex:% arg.csh a1 a2 % arg.csh a1 a2
the output after running the script is: the output after running the script is:
arg1 is a1arg1 is a1
arg2 is a2arg2 is a2
Script: arg_v1.cshScript: arg_v1.csh
#!/usr/bin/csh –f#!/usr/bin/csh –fset n = 1set n = 1 #positional index #positional indexwhile ( $n <= $#argv )while ( $n <= $#argv )
echo “Arg $n is $argv[$n]”echo “Arg $n is $argv[$n]”#increment the value of n#increment the value of n@ n++ @ n++
endend==================================Notes:Notes: # for comments# for comments After @ a space is requiredAfter @ a space is required Other ways to do it?Other ways to do it?
Script: arg_v2.cshScript: arg_v2.csh
#!/usr/bin/csh –f#!/usr/bin/csh –f
set n = 1set n = 1 #positional index #positional index
while ( $#argv > 0)while ( $#argv > 0)
echo “Arg $n is $1”echo “Arg $n is $1”
shiftshift
@ n++ @ n++
endend
Example 2
Changing the access rights of the files in a directory recursively
It is simple but is very useful
Simple Solution
#!/bin/csh -f
foreach file (`ls`)
if ( -d $file ) thenchmod –R 750 $file else chmod 750 $fileendif
end
A Solution Using Arguments
#!/bin/csh -f
if ($#argv == 0) thenecho "Please give a permission"exit 1endif
foreach file (`ls`)
if ( -d $file ) thenchmod -R $1 $file else chmod $1 $fileendif
end
A Solution Using while loop#!/bin/csh -fif ($#argv == 0) thenecho "Please give a permission"exit 1endif set file_set = `ls`set n = 1while($n <= $#file_set)set file = $file_set[$n]echo "The name of file is : $file ."if ( -d $file ) thenchmod -R $1 $fileelse chmod $1 $fileendif@ n ++end
Another Solution#!/bin/csh -fif ($#argv == 0) thenecho "Please give a permission"exit 1endif set files_set = `ls`foreach file (files_set)if ( -d $file ) thenchmod -R $1 $file else chmod $1 $fileendifend
Doesn’t Work!!
A Corrected Solution #!/bin/csh -f if ($#argv == 0) then echo "Please give a permission" exit 1 endif set files_set = `ls` foreach file ($files_set[*]) if ( -d $file ) then chmod -R $1 $file else chmod $1 $file endif end
Example 3Example 3 Task: Write a script that prints similar info. as ls Task: Write a script that prints similar info. as ls
–l, but in more user-friendly way.–l, but in more user-friendly way. Ex: Ex:
% fileinfo.csh bob (can take multiple args)% fileinfo.csh bob (can take multiple args)(Assume: ls –l bob => -rwsr-xr-x bill ….)(Assume: ls –l bob => -rwsr-xr-x bill ….)the output after running the script is:the output after running the script is:bob is a regular filebob is a regular fileyou own the fileyou own the fileyou have read permissionyou have read permissionyou have write permissionyou have write permissionyou have execute permissionyou have execute permission
Script: fileinfo.cshScript: fileinfo.csh#!/usr/bin/csh -f#!/usr/bin/csh -fset n = 1set n = 1
while ($n <= $#argv)while ($n <= $#argv) if(-d $argv[$n]) thenif(-d $argv[$n]) then echo "$argv[$n] is a directory"echo "$argv[$n] is a directory" endifendif if(-f $argv[$n]) thenif(-f $argv[$n]) then echo "$argv[$n] is a regular file"echo "$argv[$n] is a regular file" endifendif if(-o $argv[$n]) thenif(-o $argv[$n]) then echo "You own the file"echo "You own the file" elseelse echo "You do not own the file"echo "You do not own the file" endifendif
if(-r $argv[$n]) thenif(-r $argv[$n]) then echo "You have read permission"echo "You have read permission" endifendif
if(-w $argv[$n]) thenif(-w $argv[$n]) then echo "You have write permission"echo "You have write permission" endifendif
if(-x $argv[$n]) thenif(-x $argv[$n]) then echo "You have execute echo "You have execute
permission"permission" endifendif
@ n++@ n++endend
Example 4Example 4 Task: Write a script called average.csh that reads a list Task: Write a script called average.csh that reads a list
of integers on stdin and prints how many numbers were of integers on stdin and prints how many numbers were read, their sum and integer average.read, their sum and integer average.
Note: should handle the case there are not numbers read and Note: should handle the case there are not numbers read and not produce “division by 0” errornot produce “division by 0” error
Ex:Ex:% average.csh << .% average.csh << .> 10> 10> 20> 20> 30> 30> .> .3 numbers have been read3 numbers have been readthe sum is 60the sum is 60Integer average was 20Integer average was 20
Script : average.cshScript : average.csh#!/usr/bin/csh -f#!/usr/bin/csh -fset sum = 0set sum = 0set count = 0set count = 0set avg = 0set avg = 0
set num = $<set num = $<
while(($num !~ [a-z]*) && while(($num !~ [a-z]*) && ($num != ""))($num != ""))@ sum += $num@ sum += $num
@ count++@ count++ set num = $<set num = $<endend
echo "the total numbers are echo "the total numbers are $count"$count"
echo "the sum is $sum"echo "the sum is $sum"
if($count >0) thenif($count >0) then @ avg += $sum@ avg += $sum @ avg /= $count@ avg /= $count echo "Integer average is echo "Integer average is
$avg"$avg"elseelse echo "Integer average is echo "Integer average is
0"0"endifendif
Debugging C Shell ScriptDebugging C Shell Script C Shell has two command line options to help to C Shell has two command line options to help to
debug scripts by echoing each line of the script debug scripts by echoing each line of the script before actually executing it.before actually executing it. -v (verbose): echoes each line even before -v (verbose): echoes each line even before
performing variable substitutionperforming variable substitution -x: echoes each line after all substitution has been -x: echoes each line after all substitution has been
performed just before executing the actual commandsperformed just before executing the actual commands
How to use it:How to use it: % csh –xv script.csh% csh –xv script.csh #!/bin/csh –vx#!/bin/csh –vx
Or manually set echo points to avoid verbosityOr manually set echo points to avoid verbosity
Arguments to set
set echo Display each lines after variable substitution
and before execution set verbose
Display each line of script before execution, just as you typed it
Reading Assignment
Reading Chapter 10