Lesson 2 · Unit 04
Tests and loops
if and [ ], for and while read, functions and exit codes
What you practise
- `if [ ... ]
- Then
, string vs number tests,-f,-d,-z,for f in *.log,while read line`, functions and exit codes
Try a question from this lesson
Pick one
if runs a command and looks at its exit status: 0 takes the then branch. grep -q exits with 0 when it finds a match. What prints?
printf 'ok\nerror: disk\n' > app.log
if grep -q error app.log; then
echo "problems"
else
echo "clean"
fiCorrect answer
problems
Why
There is no special condition syntax here: if simply runs grep and branches on whether it succeeded. Any command can be a condition. -q keeps the matching line off the screen.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The test command
[ is a command. It checks what you ask and exits with 0 for true, so if can use it like any other command.
It needs a space around every piece, and a closing ].
Text is compared with =. Numbers use -eq, -lt and -gt.
if [ -d "$dir" ]; then
echo "a folder"
fi
[ -f notes.txt ] # a file exists
[ -z "$name" ] # an empty string
[ "$a" = "$b" ] # the same text
[ "$n" -gt 10 ] # a bigger numberConcept
Two loops
for walks a list of words: names from a glob, arguments, anything separated by spaces.
while read line takes its input one line at a time and stops when the input runs out. Feed it a file with < after done, or pipe into it.
for f in *.log; do
echo "found $f"
done
while read line; do
echo "got: $line"
done < names.txt9 more exercises in the app
- 3× multiple choice
- 1× fill the blanks
- 3× type the answer
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.