A script that takes a path must check it first. If it doesn't, a typo gives a page of errors, or work done in the wrong place.
learner@reef:~$ cat show-menu.sh
#!/bin/bash
# Usage: show-menu.sh FILE
if [ -f "$1" ]; then ← the test: is $1 a file?
cat "$1" ← yes
else
echo "no such menu: $1" >&2 ← no: write the message as an error
exit 1 ← stop, and tell the shell it failed
fi
learner@reef:~$ ./show-menu.sh menus/winter.txt
tea 2.50
cake 3.00
learner@reef:~$ ./show-menu.sh menus/winterr.txt
no such menu: menus/winterr.txt| Test | True when |
|---|---|
[ -f PATH ] | PATH is a file |
[ -d PATH ] | PATH is a directory |
[ is a command, so it needs spaces around every part, like any command: [ -f "$1" ].
"$1"/*.log is every .log file in the directory $1. Keep the * outside the quotes: inside them, it is a plain character.
-
Write
~/count-logs.sh, with#!/bin/bashon top. It takes a directory and writes how many.logfiles are in it. Make it runnable withchmod u+x, and run it:textlearner@reef:~$ ./count-logs.sh ~/logs logs: 3 -
Use
"$1"for the directory, never~/logs: it counts in any directory you give it. -
Make it check its argument first. When the argument is not a directory, it writes a message as an error and fails with
exit 1. Try./count-logs.sh ~/nope.
Objectives
- Count the
.logfiles in~/logs. - Count them in any directory you give it.
- Refuse a directory that does not exist.