V Lecture 4 — scripting
V Scripting
V quick overview of for, if, and while
* for VAR in LIST
do
COMMANDS
done
* for (( INITIALIZE; TEST; INCREMENT ))
do
COMMANDS
done
V if COMMAND
then
COMMANDS
elif COMMAND
then
COMMANDS
else
COMMANDS
fi
* when if’s COMMAND succeeds (i.e., exit status of 0), do then COMMANDS
* test (also written [ ]) provides a lot of useful tests
* use ! for negation, || for or, && for and
V while COMMAND
do
COMMANDS
done
* while also treats an exit status of 0 as true
V pgplot example
* conditional to check for directory (-d)
* for loop
V use of variable inside a string
* " " allow shell substitutions (e.g., variables), ' ' do not
* #!/bin/bash, chmod +x
V exercise: pgplot extensions
* compute number of files instead of hard-coding
(ls pgplot* | wc -l)
* generate a file that lists the copied files in order
(> filename to initialize, echo "…" >> filename inside loop)
V thumbnail example
V processing arguments
V $# is the variable for the number of arguments
* doesn’t count $0
* $0 is the command
V $1, $2, … are the arguments
* $@ is the list of all the arguments (not including $0)
* if [ $# -eq 0 ], for arg in $@
* redirect stdout to stderr (1>&2)
V exit
* terminates the script, takes a number as an argument to use as the exit status
V $? is the variable for the most recent exit status
* by convention, an exit status of 0 means success, and anything else means some kind of failure
V parameter substitution
* ${parameter#word} deletes shortest match for word from the beginning of parameter (## for longest match)
* ${parameter%word} deletes shortest match for word from the end of parameter (%% for longest match)
V ${parameter/pattern/string} replaces first match for pattern in parameter with string
* (use ${parameter//pattern/string} to replace all matches)
* if pattern begins with #, it must match at the beginning of parameter
* if pattern beings with %, it must match at the end of parameter
V exercise: thumbnail extension
* check that image file exists
(conditional to check for file: -f, continue)