Sub topic 6
Loops and conditionals
This chapter assumes you can read a short script and know what a variable is. Loops and conditionals are the two constructs that make a script act on more than one item or react to a result. Without them, a script is only a list of commands.
Conditionals: making a decision
A conditional runs a block of code only when a test is true. Nearly every language uses the same shape: if, an optional else, and a block of commands. Only the syntax differs.
In a Windows batch file, the test often checks %ERRORLEVEL%. This is the exit code of the previous command, and 0 usually means success.
@echo off
REM Map a network drive and confirm it
net use Z: \\fileserver\shared /persistent:yes
if %ERRORLEVEL% EQU 0 (
echo Drive Z: mapped.
) else (
echo Mapping failed.
)EQU means "equal to". Batch uses word operators such as EQU and NEQ, while PowerShell uses -eq and -ne. Bash uses -eq for numbers inside [ ]. Python uses ==.
Loops: repeating work
A loop repeats a block of code. Two kinds appear on the exam.
- A
fororforeachloop runs once for each item in a collection, such as files or services. - A
whileloop runs for as long as a test stays true.
This PowerShell loop visits each stopped service in turn:
# List stopped services
$stopped = Get-Service | Where-Object { $_.Status -eq 'Stopped' }
foreach ($svc in $stopped) {
Write-Output $svc.Name
}This Bash script combines a loop with a conditional. It copies each text file only if the backup folder exists.
#!/bin/bash
# Copy text files from Documents to a backup folder
src="$HOME/Documents"
dest="/mnt/backup"
if [ -d "$dest" ]; then
for f in "$src"/*.txt; do
cp "$f" "$dest"
done
echo "Backup finished for user $USER"
else
echo "Backup folder missing"
fiPython uses indentation instead of braces or fi. This while loop retries a task up to three times:
attempts = 0
while attempts < 3:
attempts += 1
print(f"Attempt {attempts}")Common errors
- Infinite loops. A
whileloop whose test never becomes false runs until you stop it. In the Python example, removingattempts += 1would cause this. - Wrong comparison operator. Using
=where a language expects==, or-eqwhere it expectsEQU, gives errors or wrong results. - Missing structure. A forgotten
fi, closing brace,)or indentation level stops the script or changes its meaning.
Exercise
A Bash script contains the line for f in "$src"/*.txt; do. What does this loop do, and which construct would you add to run the copy only when a destination folder exists?
Show answer
It runs the commands between do and done once for each .txt file in the source folder, storing each file name in f. To check for the destination folder, wrap the loop in a conditional such as if [ -d "$dest" ]; then ... fi.