5.
Recall the version of the 'for' syntax in which you type "for" and
a variable name, but nothing else on the line: This goes through all
command-line arguments.
Write a shell script in sh which goes through its command-line arguments
(which are supposed to be file names) and
deletes (with 'rm')
all files which
contain (according to grep) the string "spatula".
Solution:
for i
do
if grep spatula "$i" >/dev/null
then
rm "$i"
fi
done
Notes:
- Backquotes are not applicable here; we are testing the exit status of the
grep, not its output to stdout
- Instead of the output redirection to /dev/null, you could use the -s or
-q options
- "--" should perhaps be used to avoid doing funny things with command-line
options beginning with a '-', but those file names cause problems in general
and we usually insist that the user take care of it, e.g. by prefixing the
file name with "./"
- However, the quoting of the variable interpolation is essential, both in
the grep and in the rm, else this command is unuseable on files with spaces in
their names
(i.e. in this case it's not merely about extra requirements on the user (not
to mention the fact that file names with spaces are common these days, unlike
file names beginning with '-'))
[sample midterm from Winter 2011]