Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Variables, conditions and loops

By the end of this chapter, you'll be able to

  • Use variables and a script's arguments
  • Write conditions with if and [[ ]] tests
  • Repeat actions with for and while
  • Protect variables with quotes

Variables and arguments

A variable is created with no space around the =, and read with $:

school="Kati High School"
students=42
echo "Welcome to $school: $students students enrolled."
echo "In a year: $((students + 8)) students."
Welcome to Kati High School: 42 students enrolled.
In a year: 50 students.

$(( ... )) computes an integer expression. To store the result of a command in a variable, you write $(command):

mkdir -p dropbox
touch dropbox/homework1.txt dropbox/homework2.txt dropbox/grades.pdf
count=$(find dropbox -type f | wc -l | tr -d " ")
echo "Files dropped off: $count"
Files dropped off: 3

Here, tr -d " " removes the spaces that some versions of wc add before the number. In a script, the arguments passed on the command line are called $1, $2…; $# gives their number and $0 the script's name.

Conditions

if runs a block if a condition is true. In Bash, tests are written between double brackets [[ ... ]], with spaces inside:

free_space=12   # as a percentage
if [[ $free_space -lt 10 ]]; then
  echo "ALERT: disk almost full"
elif [[ $free_space -lt 20 ]]; then
  echo "Warning: less than 20% free"
else
  echo "Disk is healthy"
fi
Warning: less than 20% free

The most useful tests:

Numbers:  -eq (equal)  -ne (not equal)  -lt (<)  -le (<=)  -gt (>)  -ge (>=)
Text   :  == (equal)   != (different)   -z "$t" (empty)   -n "$t" (not empty)
Files  :  -f file (exists, regular file)  -d folder (exists, folder)
          -r (readable)  -w (writable)  -x (executable)

Careful: to compare numbers, use -lt, -gt…; < and > compare text in alphabetical order.

Loops

for goes through a list, for example all the files in a folder:

for file in dropbox/*.txt; do
  echo "To mark: $(basename "$file")"
done
To mark: homework1.txt
To mark: homework2.txt

while repeats as long as a condition is true, and is often used to read a file line by line:

printf "Awa;Final year\nKofi;Year 11\nLina;Final year\n" > class.csv
while IFS=";" read -r name level; do
  echo "$name is in $level"
done < class.csv
Awa is in Final year
Kofi is in Year 11
Lina is in Final year

IFS=";" sets the field separator, and read -r reads a line without interpreting backslashes.

There are no lines left: read fails, the condition becomes false and the loop stops.

Step 6 of 6
Text description of the animation
  1. read reads the first line and splits it on the semicolon.
  2. The two pieces go into name and level; echo prints them.
  3. Back to the start: read reads the next line.
  4. Same processing for Kofi.
  5. Then for Lina.
  6. There are no lines left: read fails, the condition becomes false and the loop stops.

Mini-lab: counting the homeworkTerminal simulator

Terminal

Click “Run”: the commands run in a fresh terminal, in your home folder /home/awa. Type “help” for the list of commands.

Teaching simulator: it reproduces the essential Linux commands in your browser, with nothing to install · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

The simulator does not know loops: to try them, use a real terminal (Linux, macOS or a hosting terminal).

Your turn

Worked exercise

Worked exercise: sorting the dropped-off files

Write a script that goes through the files of the dropbox/ folder and prints, for each one, PDF: name or Text: name depending on its extension, then the total number of files of each kind.

Hint 1
Inside [[ ]], == accepts a pattern: [[ $f == *.pdf ]] is true if the name ends with .pdf.
Hint 2
Keep two counters and increment them with pdf=$((pdf + 1)).
Show the solution and common mistakes
pdf=0
text=0
for f in dropbox/*; do
  if [[ $f == *.pdf ]]; then
    echo "PDF: $(basename "$f")"
    pdf=$((pdf + 1))
  else
    echo "Text: $(basename "$f")"
    text=$((text + 1))
  fi
done
echo "Total: $pdf PDF, $text others"
PDF: grades.pdf
Text: homework1.txt
Text: homework2.txt
Total: 1 PDF, 2 others

Common mistakes:

  • Writing [[$f == *.pdf]] without spaces after [[ and before ]]: Bash no longer recognises the test command.
  • Putting the pattern in quotes, [[ $f == "*.pdf" ]]: the star becomes an ordinary character, and no file matches.

Summary

  1. 1A variable is created with name=value, without spaces, and read with $name.
  2. 2$(command) captures a command's result; $(( )) computes on integers.
  3. 3if [[ ]] tests numbers (-lt, -gt…), text (==, -z) and files (-f, -d).
  4. 4for goes through a list; while read reads a file line by line.
  5. 5Always put variables in double quotes: "$variable".

Your progress is saved on this device. Create a free account to keep your progress on all your devices.