[ ] also asks about files. Chapter 1 used -f and -d. Two more:
| Test | True when the path… |
|---|---|
[ -f PATH ] | is a file |
[ -d PATH ] | is a directory |
[ -s PATH ] | is not empty |
[ -r PATH ] | can be read by you |
[ ! -f PATH ] | is not a file. ! turns any test around |
learner@reef:~$ [ -s todo.txt ]; echo $?
1 ← todo.txt is empty
learner@reef:~$ [ -r /etc/shadow ]; echo $?
1 ← only root may read itWrite ~/check-file.sh FILE. It checks a file before anyone uses it:
| The path | It prints | Exit code |
|---|---|---|
| isn't a file | not a file: FILE | 1 |
| is empty | empty: FILE | 1 |
| can't be read | unreadable: FILE | 1 |
| anything else | ok: FILE | 0 |
-
Write one
if, aneliffor each next row, and anelseforok. Write"$1"in quotes in every test. -
Make it runnable and try it:
textlearner@reef:~$ chmod u+x ~/check-file.sh learner@reef:~$ ./check-file.sh shop/prices.txt ok: shop/prices.txt -
Try
shop,shop/orders.txtandshop/safe.txt.
Objectives
- A file:
ok. Anything else, like the directoryshop:not a file, exit code 1. - An empty file:
empty, exit code 1. - A file you can't read:
unreadable, exit code 1.