Course / The terminal and the language
Check before you act
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/04-03-shell-conditions-and-tests
cd 04-03-shell-conditions-and-tests
gonomicon submitGoal
Your script is started with one argument, a path, like sh answer.sh testdata/report.txt. Print found: PATH when that path is an existing file, and missing: PATH when it is not.
Example
If testdata/report.txt exists, then sh answer.sh testdata/report.txt prints:
found: testdata/report.txt
If testdata/nothing.txt does not exist, then sh answer.sh testdata/nothing.txt prints:
missing: testdata/nothing.txt
In both cases PATH is the argument exactly as it was given, including any spaces.
Rules
- Edit
answer.sh. The path is the first argument,$1. - Use an
ifwith the-ftest inside[ ], and anelsefor the other case. - Print exactly one line, using
printf:found:ormissing:followed directly by the path. - Put double quotes around
$1everywhere you use it. A path liketestdata/my notes.txtcontains a space and must stay in one piece. The test creates that file for you when it runs. - The brackets need a space after
[and before]. - A folder is not a file. If the path names a folder, print
missing: PATH. The-ftest already behaves this way. - Do not print anything else, not even a blank line.
What you'll practice
if, else, fi, the -f test inside [ ], $1, and quoting.
Run it
gonomicon fetch week-1/04-03-shell-conditions-and-tests
cd 04-03-shell-conditions-and-tests
gonomicon test
gonomicon submit
Hints
- The
-ftest succeeds when a path is a regular file. It goes inside brackets with spaces around everything:[ -f "$1" ]. - Use
if [ -f "$1" ]; then ... else ... fi. Keep the double quotes around$1so a path with spaces stays one item. if [ -f "$1" ]; then printf 'found: %s\n' "$1"; else printf 'missing: %s\n' "$1"; fi, written across several lines.