Bitpath

Lesson 2 · Unit 04

Tests and loops

if and [ ], for and while read, functions and exit codes

12 exercisesabout 3 min

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?

shell
printf 'ok\nerror: disk\n' > app.log
if grep -q error app.log; then
  echo "problems"
else
  echo "clean"
fi

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.

shell
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 number

Concept

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.

shell
for f in *.log; do
  echo "found $f"
done

while read line; do
  echo "got: $line"
done < names.txt

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy