Course outline
Course / The terminal and the language

Check before you act

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

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 if with the -f test inside [ ], and an else for the other case.
  • Print exactly one line, using printf: found: or missing: followed directly by the path.
  • Put double quotes around $1 everywhere you use it. A path like testdata/my notes.txt contains 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 -f test 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

  1. The -f test succeeds when a path is a regular file. It goes inside brackets with spaces around everything: [ -f "$1" ].
  2. Use if [ -f "$1" ]; then ... else ... fi. Keep the double quotes around $1 so a path with spaces stays one item.
  3. if [ -f "$1" ]; then printf 'found: %s\n' "$1"; else printf 'missing: %s\n' "$1"; fi, written across several lines.

Something wrong with this lesson? Report a problem