Course contents · Lesson 17 of 19

Bash Variables, Loops and Conditions Explained

Shell Scripting · Lesson 17 of 19 · 12 min Hands-on

Your server's /var/log holds dozens of files, and you want to know which are getting too big. The script from lesson 16 cannot remember a value, repeat a step or make a choice. Bash variables, loops and conditions add those three, and this lesson ends with a script that warns about large files.

Variables: name=value, then "$name"

A variable is a name that holds a value. You create one with name=value and read it back with a $ in front of the name. As in lesson 16, $ at the start of a line stands for the prompt:

$ name=Asha
$ echo "Hello, $name"
Hello, Asha
$ name = Asha
bash: name: command not found

There must be no spaces around the =: with spaces, bash runs name as a command, with = and Asha as its arguments. Names hold letters, digits and underscores, never start with a digit, and are case-sensitive.

Command substitution, $(command), runs a command and puts its output in that spot, minus any line breaks at the end. Arithmetic expansion, $((…)), does whole-number maths, and inside it names need no $:

$ today=$(date +%F)
$ echo "$today"
2026-12-02
$ count=3
$ count=$((count + 1))
$ echo "$count"
4

date +%F prints the date as year-month-day, so yours will differ. Bash stores every value as text: count holds the character 4, and only $((…)) or a number test reads it as a number. Settings meant to be changed, such as a limit, are often written in capitals. In the diagram, each variable is a jar: the lid is its name.

Three jars, each a variable with its name on the lid. The jar name, filled by name=Asha, holds the text Asha. The jar count, filled by count=3, holds 3, a number kept as text. The jar today, filled by today=$(date +%F), holds a command's output, such as 2026-12-02, an illustrative date. Below, echo Hello, $name copies the value out and prints Hello, Asha, while name = Asha with spaces fails, because bash runs name as a command
Reading $name copies the value out; the jar stays full until you assign something new.

Conditions: if, elif and else

if runs a command and checks its exit code (lesson 16): 0 runs the commands after then, anything else those after else, and fi closes the block. The command is usually [[ … ]], Bash's test, which ends with 0 when its condition is true and 1 when it is false:

if [[ -f /etc/hosts ]]; then
  echo "found /etc/hosts"
fi

-f is true when the path exists and is a regular file, not a folder; -d tests for a folder, and ! in front reverses the result. Keep the spaces inside the brackets: [[-f is one word, a command that does not exist.

Compare numbers with -eq (equal), -ne (not equal), -lt, -le, -gt and -ge (less than, less or equal, greater than, greater or equal). Compare text with == and !=. Never use > for numbers: inside [[ ]] it compares text in dictionary order, so [[ 10 > 9 ]] is false, because 1 sorts before 9.

elif, short for else if, adds more tests. Bash tries them in order and runs only the first branch whose test is true, like a light showing one colour. Here disk is an illustrative 82 percent:

disk=82
if [[ $disk -ge 90 ]]; then
  echo "red: clean up now"
elif [[ $disk -ge 75 ]]; then
  echo "amber: keep an eye on it"
else
  echo "green: fine"
fi

The first test fails and the second succeeds, so this prints amber: keep an eye on it.

Loops: for and while

A loop repeats commands. A for loop runs the commands between do and done once for each word in a list, with the loop variable set to the current word:

$ for dish in cup bowl plate; do echo "Washing the $dish"; done
Washing the cup
Washing the bowl
Washing the plate

Scripts usually loop over files with a wildcard, a pattern in which * stands for any characters: for f in /var/log/*.log. Before the loop starts, bash replaces *.log with the matching names in alphabetical order, so the pile is fixed up front. If nothing matches, the pattern stays as plain text, which is why scripts test each name before using it.

A while loop repeats as long as its command succeeds. while read -r line handles a file one line at a time: read puts the next line in the variable and fails at the end of the file, which ends the loop. -r keeps backslashes as they are, and < servers.txt after done feeds the lab's file to the whole loop:

$ while read -r server; do echo "Checking $server"; done < servers.txt
Checking web1
Checking web2
Checking db1

A while loop can also count, with a test and a variable that changes every round:

count=1
while [[ $count -le 3 ]]; do
  echo "Plate $count"
  count=$((count + 1))
done

This prints Plate 1, Plate 2 and Plate 3. Leave out the count= line and the test never fails: the loop runs forever, until Ctrl+C stops it (lesson 10).

Quoting: why "$file" matters

Without double quotes, bash splits a variable's value at spaces, tabs and line breaks into separate words, and expands any wildcard in it. Double quotes keep the value as one word. Lesson 16's printf line, one argument per bracket, shows the difference:

$ file="old app.log"
$ printf '[%s]\n' $file
[old]
[app.log]
$ printf '[%s]\n' "$file"
[old app.log]

Unquoted, printf got two arguments. rm $file would try to delete a file called old and another called app.log, which may be a different, real file. So write "$file" whenever a variable holds a name or a path.

A wildcard's results are never split, so for file in "$folder"/* hands the loop old app.log as one name; the * stays outside the quotes so it still expands. Inside [[ ]] bash does not split either, so the number tests leave $size bare.

Putting it together: check-sizes.sh

The lab's check-sizes.sh uses all of it: it prints a line for each entry in a folder, warns about every file over LIMIT bytes, and ends with a count:

#!/usr/bin/env bash
# check-sizes.sh: list a folder's files and warn about large ones.
# Usage: ./check-sizes.sh FOLDER
set -euo pipefail

LIMIT=1000000   # bytes (1 MB): change it and run again

if [[ $# -ne 1 ]]; then
  echo "Usage: $0 FOLDER" >&2
  exit 1
elif [[ ! -d "$1" ]]; then
  echo "Not a folder: $1" >&2
  exit 1
fi

folder="$1"
large=0

for file in "$folder"/*; do
  if [[ ! -f "$file" ]]; then
    echo "skip: $file is not a regular file"
    continue
  fi
  size=$(stat -c %s "$file")   # on macOS: stat -f %z "$file"
  if [[ $size -gt $LIMIT ]]; then
    echo "WARNING: $file is $size bytes, over $LIMIT"
    large=$((large + 1))
  else
    echo "ok: $file is $size bytes"
  fi
done

echo "Files over the limit: $large"

The guard uses if and elif to stop with exit code 1 unless you give exactly one argument and it is a folder. In the loop, continue skips the rest of the body and moves to the next name, so a folder such as /var/log/apt gets only a skip line. stat -c %s prints a file's size in bytes; on macOS, use the comment's version.

In the flowchart, follow one name through the loop body: every path ends at the same question.

Flowchart. Take the next name from $folder/*. Is it a regular file? If no, print a skip line, and continue skips the rest. If yes, read its size in bytes with stat. Is the size over the limit? If yes, print WARNING and add 1 to large; if no, print ok. All paths meet at: more names? If yes, the next round starts; if no, print the summary, Files over the limit: $large. Chips note that $folder/* gives every name, sorted, and that LIMIT=1000000, 1 MB, is set at the top
Skip, ok or WARNING: whichever branch runs, the loop then moves on.

The trace shows every variable after each line, for three of /var/log's entries. Notice that size still says 1450000 while apt is skipped.

A trace of ./check-sizes.sh /var/log, trimmed to three entries, with LIMIT=1000000. large=0 sets large to 0. The for line sets file to /var/log/app.log. stat sets size to 1450000. The -gt test is true, so it prints WARNING: /var/log/app.log is 1450000 bytes, over 1000000, and large becomes 1. The second name, /var/log/apt, is not a regular file: it prints a skip line and continues, and size keeps 1450000. The third name, /var/log/old app.log, has size 28, the -gt test is false, and it prints an ok line. The last line prints Files over the limit: 1
A variable keeps its value until a line assigns it a new one.

Check yourself

Why is [[ 9 > 10 ]] true, and what should you write instead?

> compares text in dictionary order, and the character 9 sorts after 1. [[ 9 -gt 10 ]] compares the values as numbers, so it is false.

The stat line in check-sizes.sh used $file without quotes. What happens with a file called /var/log/my notes.txt?

stat gets two names, /var/log/my and notes.txt, finds neither, and set -e stops the script. "$file" passes the one real name.

The loop already takes its names from a wildcard. Why does the script still test -f?

The wildcard matches folders too, such as apt, and in an empty folder it stays as the plain text folder/*. -f lets only real files reach stat.