Course / The terminal and the language
Build a check you can reuse
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-05-shell-functions-and-exit-statuses
cd 04-05-shell-functions-and-exit-statuses
gonomicon submitGoal
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
-ftest 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 withprintf. 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
$1everywhere 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
missingor any other message. - You do not need an
else.set -edoes 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
- 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. - Put
set -eat the top. Then, ifcheck "$1"fails, the script stops right there and theprintfafter it never runs. set -e, thencheck() { [ -f "$1" ]; }, thencheck "$1", thenprintf 'OK: %s\n' "$1". Write it across several lines.