|
|
|
Lecture 4 — scripting
|
|
|
|
|
Scripting
|
|
|
|
|
quick overview of for, if, and while
|
|
|
|
|
for VAR in LIST do COMMANDS done
|
|
|
|
|
for (( INITIALIZE; TEST; INCREMENT )) do COMMANDS done
|
|
|
|
|
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
|
|
|
|
|
while COMMAND do COMMANDS done
|
|
|
|
|
while also treats an exit status of 0 as true
|
|
|
|
|
pgplot example
|
|
|
|
|
conditional to check for directory (-d)
|
|
|
|
|
for loop
|
|
|
|
|
use of variable inside a string
|
|
|
|
|
" " allow shell substitutions (e.g., variables), ' ' do not
|
|
|
|
|
#!/bin/bash, chmod +x
|
|
|
|
|
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)
|
|
|
|
|
thumbnail example
|
|
|
|
|
processing arguments
|
|
|
|
|
$# is the variable for the number of arguments
|
|
|
|
|
doesn’t count $0
|
|
|
|
|
$0 is the command
|
|
|
|
|
$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)
|
|
|
|
|
exit
|
|
|
|
|
terminates the script, takes a number as an argument to use as the exit status
|
|
|
|
|
$? 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
|
|
|
|
|
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)
|
|
|
|
|
${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
|
|
|
|
|
exercise: thumbnail extension
|
|
|
|
|
check that image file exists (conditional to check for file: -f, continue)
|
|
|