Goals
In this session you will:
- do shell arithmetic
- use subroutines
- control variable scope
- reuse components
- getopts
POST
Approx 30 mins will be allotted for this POST.
- log into your Solaris machine
- write a script called day3post.sh
- the script should find each .sh file in your directory and back it up:
- store the path to your backup dir in a variable for ease, resuse, and accuracy.
- the backed up file should have a date-based extension of some kind. For this exercise, filenames should have no spaces.
- bonus: keep only the 3 most recent backups of any particular file...
use math
use the STDOUT of expr for math;
use exitcodes
use $? for comparison.
Intro to scope
- parents spawn children
- children inherit environment by value
- children cannot affect the namespace of the parent
- children cannot affect the pwd of the parent
subroutines
Pass args in as if on the commandline: subname arg1 arg2
subname () {
# receive parms by position $1, $2, etc
# or by $* or "$@"
return returnvalue
}
Grab the return value from $? immediately after calling the function.
Note this difference
$* each arg separately
"$*" all args together
$@ same as $*
"$@" correctly parses quoted args
variable scope
- save positional vars ASAP
- may be able to localize the variable with
local
- if not, maintain separate namespace
component reuse
Note that when you run something in a subshell the vars (including function names) are limited to that subshell.
. sourcefile
getopts
getopts is meant to be run in a loop
- a
case construct is used used to associate each switch value with a variable.
#set some default vars here
#start looping to assign input
while getopts n:r:s: option
do
case "$option"
in
n) name="$OPTARG";;
r) rank="$OPTARG";;
s) serialnumber="$OPTARG";;
*) echo "error in options processing";;
esac
done
echo "name is $name";
echo "rank is $rank";
echo "serial is $serialnumber";
Homework
- restricted shell
- subshells and inline commands
- other shells (esp. ksh, but also bash, csh)
http://www.mousetrap.net/syllabus/shell/day3.html
$Id: day3.orb,v 1.13 2002/11/26 23:47:45 mouse Exp $
Remember, your login is based on your machine's hostname, not on any other number.
~/[initials] refers to the subdirectory under your homedir, named after your initials. Everything except for .dotfiles will be stored in your ~/[initials] directory.