| Name: _____________________ | Class: CET 421 |
| SSN/ID: _____________________ | Section & Group: ____________ |
This week we'll continue with some more advanced shell scripting control strucutres, including conditionals, loops, etc. You'll be building upon the shell script file you made last week, add.sh.
if-then-else
Just like other programming languages, shell scripts can have conditional statements (if-then-else) and loops (while and foreach).
Now we're going to add an extra bit of code to the add.sh script from the previous lab. That script took in two numbers as arguments from the command-line and added them. But we never checked that the user had entered at least two arguments; if they ran the script and didn't enter two arguments, it would just output an unrecognizable error. Here, we'll use an if statement to output a better error if at least two arguments aren't passed:
if ($#argv != 2) then
echo "You must give exactly two parameters!"
else
set num1 = $argv[1]
set num2 = $argv[2]
endif
Replace the two lines in the code that set the num1 and
num2 variables with the above. As you can see, it checks
that the argv array has at least two elements. If it doesn't,
we echo an error line; otherwise, it'll simply set the
variables.
Example with a for loop
#! /bin/csh -f
######################################################################
#
# Script to find specified file
#
######################################################################
set f = $1
foreach d (*)
if (-e $d/$f) then
echo "FOUND: $d/$f"
exit(0)
endif
end
echo "$f not found in subdirectories."
Save this as find_file.sh in your HOME directory. This takes
one argument, which is the name of a file to search for, which is then
stored in the variable f. It then searches through all
subdirectories of the current directory looking for a file with that
name.
In the line foreach d (*), the * is a wild card, so it would expand to a list of all files in the current directory.
In the line if (-e $d/$f) then, the -e means existance; in other words, we are asking if the file $d/$f exists. If we type ./find_file.sh test.txt, as in the example above, $f would be test.txt and $d would start out as bin. So, we would be asking if the file bin/test.txt exists. Because it's in a for each loop, it'll try the if statement either until it finds one and it exits(0) or until there are no more directories to try.
Writing your own script
Using what you've learned in all the labs, you are now going to write a script yourself that does the following:
Hand In: This lab handout with the answers filled in attached
to a listing of your final programs
(use the enscript command from your Programming Style Sheet to print it out:
enscript -E -G -2rj -M Letter -PECT2_PS <filename>. You can also use a2ps as in: a2ps <filename>).