Course outline
Course / The terminal and the language

Build a check you can reuse

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-05-shell-functions-and-exit-statuses
cd 04-05-shell-functions-and-exit-statuses
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. Write a function that checks whether the path is a file, and use set -e so that the script prints OK: PATH for a file but prints nothing and stops with a failure status for anything else.

Example

If testdata/config.txt exists, then sh answer.sh testdata/config.txt prints:

OK: testdata/config.txt

and ends with status 0 (success).

If testdata/ghost.txt does not exist, then sh answer.sh testdata/ghost.txt prints nothing at all and ends with a non-zero status (failure).

Rules

  • Edit answer.sh. The path is the first argument, $1.
  • Start the script with set -e, so it stops at the first failed command.
  • Define a function that checks the path with the -f test inside [ ]. A function hands back the status of its last command, so a function whose last command is a failed test counts as failed.
  • Call your function with the path, then print the OK: line with printf. Do it in that order, so a failed check stops the script before anything is printed.
  • Print exactly one line, OK: followed directly by the path, and only when the path is a file.
  • Put double quotes around $1 everywhere you use it. A path can contain spaces.
  • A folder is not a file. A folder path prints nothing and fails.
  • Nothing may reach the screen when the check fails. Do not print missing or any other message.
  • You do not need an else. set -e does the stopping for you.
  • Do not edit any file. Your script only prints.

What you'll practice

Functions, set -e, exit statuses, the -f test, $1, and quoting.

Run it

gonomicon fetch week-1/04-05-shell-functions-and-exit-statuses
cd 04-05-shell-functions-and-exit-statuses
gonomicon test
gonomicon submit

Hints

  1. A function is a named block: check() { ... }. Its status is the status of the last command inside it, and [ -f "$1" ] hands back 0 for a file and 1 otherwise.
  2. Put set -e at the top. Then, if check "$1" fails, the script stops right there and the printf after it never runs.
  3. set -e, then check() { [ -f "$1" ]; }, then check "$1", then printf 'OK: %s\n' "$1". Write it across several lines.

Something wrong with this lesson? Report a problem