Sub topic 6
Loops and Conditionals
This chapter covers the two constructs that make a script decide and repeat: conditionals and loops. It assumes you can run commands in the Windows command prompt, PowerShell, and a Linux shell, that you know basic file paths, and that you have seen variables and comments in the previous chapters. For the A+ Core 2 exam you must recognize these constructs in a short script and predict what it does. You will not usually have to write one from scratch.
Why control flow matters
A script without control flow runs the same commands in the same order every time. That is a list of commands. Control flow lets a script react to what it finds.
- A conditional runs a block of code only if a test is true. The usual keywords are
if,else, andelif(orelseif). - A loop runs a block of code repeatedly. A
forloop repeats once for each item in a collection or a count. Awhileloop repeats as long as a test stays true.
Most support scripts combine the two. For example, a script loops over every file in a folder and, for each one, tests whether the file is old enough to delete.
Conditionals in four languages
Each language has the same idea with different punctuation. The exam often tests whether you can tell the languages apart by their syntax.
Batch
A batch script checks the exit code of the last command through %ERRORLEVEL%. By convention, an exit code of 0 means success. The comparison operators are words: EQU (equal), NEQ (not equal), LSS (less than), GTR (greater than).
@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.
)The opening parenthesis must sit on the same line as if and the closing parenthesis before else. Moving else to its own line is a common syntax error in batch files.
PowerShell
PowerShell uses braces for blocks and dash-prefixed operators: -eq, -ne, -lt, -gt, -le, -ge. It does not use == or > for comparison, because > redirects output to a file.
$free = (Get-PSDrive C).Free / 1GB
if ($free -lt 10) {
Write-Output "Low disk space on C:"
} elseif ($free -lt 50) {
Write-Output "Disk space is getting low"
} else {
Write-Output "Disk space is fine"
}Bash
Bash puts the test in square brackets with spaces inside them, ends the block with fi, and uses then. Numeric operators are also dash-prefixed (-eq, -lt), while string comparison uses = or ==.
#!/bin/bash
# Warn if the backup folder is missing
dest="/mnt/backup"
if [ -d "$dest" ]; then
echo "Backup folder found."
else
echo "Backup folder missing: $dest"
fiThe -d test is true when the path is a directory. Other common tests are -f (regular file exists) and -e (anything exists at that path).
Python
Python uses a colon after the condition and indentation to mark the block. There are no braces and no closing keyword. It uses elif and the symbols ==, !=, <, >.
import os
disk_free_gb = 8
if disk_free_gb < 10:
print("Low disk space")
elif disk_free_gb < 50:
print("Getting low")
else:
print("Disk space is fine")If the indentation is wrong, the script either fails with an IndentationError or does something different from what you intended.
Comparing the syntax
| Language | Block markers | "Equal" operator | End of an if block |
|---|---|---|---|
| Batch | `( )` | `EQU` or `==` | closing `)` |
| PowerShell | `{ }` | `-eq` | closing `}` |
| Bash | `then` | `-eq` (numbers), `=` (strings) | `fi` |
| Python | `:` plus indentation | `==` | end of indentation |
Loops in four languages
The `for` loop
A for loop is the best fit when you know what you are looping over: a list of files, a list of computers, or a count.
The PowerShell version stores the output of a command and loops over each item:
# List stopped services
$stopped = Get-Service | Where-Object { $_.Status -eq 'Stopped' }
foreach ($svc in $stopped) {
Write-Output $svc.Name
}Here $svc is the loop variable. On each pass it holds the next service. $_ inside the braces after Where-Object means "the current item in the pipeline".
The Bash version loops over files that match a pattern:
#!/bin/bash
# Copy text files from Documents to a backup folder
src="$HOME/Documents"
dest="/mnt/backup"
for f in "$src"/*.txt; do
cp "$f" "$dest"
done
echo "Backup finished for user $USER"The loop body sits between do and done. Quoting "$f" keeps file names that contain spaces from being split into separate words.
The Python version loops over a count, using range():
import os
name = "workstation01" # string
count = 3 # integer
active = True # boolean
for i in range(count):
print(f"{name}: check {i + 1}")
if active:
print("PATH is", os.environ.get("PATH"))range(3) produces 0, 1, 2. That is why the script prints i + 1, so the checks are numbered 1 to 3. Counting from 0 is a frequent source of off-by-one errors.
The `while` loop
A while loop is the better fit when you do not know in advance how many passes you need, such as waiting for a service to start or retrying a connection.
#!/bin/bash
# Try to reach a host up to 5 times
tries=0
while [ $tries -lt 5 ]; do
if ping -c 1 192.168.1.10 > /dev/null; then
echo "Host is up."
break
fi
tries=$((tries + 1))
sleep 2
doneThis script shows three things:
- The loop test (
$tries -lt 5) is checked before every pass. trieschanges inside the loop. If nothing in the body ever changes the tested value, the loop never ends.breakleaves the loop early. Its partnercontinueskips the rest of the current pass and starts the next one.
Common errors
These are the mistakes that turn up most often in support scripts and in exam questions.
- Using the wrong operator for the language. Writing
if ($x == 5)in PowerShell fails, because PowerShell needs-eq. Writingif [ $x -eq 5 ]in Python fails for the opposite reason. - Using
=where a comparison is needed. In Python, a single=assigns a value, and==compares. Python raises a syntax error if you use=inside aniftest. - Missing spaces in Bash tests.
[$x -eq 5]fails. The brackets need a space on each side, because[is a command and]is its last argument. - Unquoted variables. If
$destis empty or contains a space,[ -d $dest ]can behave differently from what you expect. Quote it as"$dest". - Off-by-one counts.
range(5)gives five values, from 0 to 4, not 1 to 5. - A loop that cannot end. The tested value never changes, or the exit condition can never be true.
- Not checking whether a command succeeded. The batch example tests
%ERRORLEVEL%for this reason. Without that test, the script prints nothing about a failure and carries on.
Reading a script on the exam
When the exam shows a short script, work through it in this order:
- Identify the language from the extension (
.bat,.ps1,.sh,.py) or from the syntax (fi,$var,REM,:plus indentation). - Find the loop and name what it iterates over.
- Find each conditional and decide what it tests.
- Trace one pass with sample values, then a second pass with different values.
Connecting to support work
Loops and conditionals are what make the common use cases practical. A login script can map a drive only if the drive letter is not already in use. A cleanup script can loop through user profiles and delete only those older than a set age. An information-gathering script can loop through a list of computer names and record which ones respond. A later chapter on remote monitoring and management (RMM) covers how these scripts are pushed out to many machines at once. The same property that makes loops useful, doing a task many times without a person watching, also means that a mistake is repeated many times. That is why the chapter on risks asks you to test a script on a single machine first.
Exercise
A Bash script contains while [ $n -lt 10 ]; do echo "check"; done, and nothing in the loop changes n. Starting with n=0, what happens when the script runs, and how do you stop it?
Show answer
The test 0 -lt 10 is always true because n never changes, so the loop is infinite and prints "check" repeatedly. Press Ctrl+C to stop it. The fix is to change n inside the loop, for example with n=$((n + 1)).
Exercise
Which language does this fragment belong to, and what does it do? if ($free -lt 10) { Write-Output "Low" }
Show answer
It is PowerShell, recognizable by the $ variable, the dash-prefixed -lt operator, and the braces. It prints "Low" when the value of $free is less than 10.
Exercise
In a batch file, what does if %ERRORLEVEL% EQU 0 test, and what does a value of 0 normally mean?
Show answer
It tests the exit code of the previous command. A value of 0 normally means the command succeeded, so the true branch is the success path.