Sub topic 3
Comments and Variables
This chapter covers two constructs that appear in every script: comments and variables. You will see how each of the five script types writes them. It also covers the errors that cause most script failures on the job and on the exam.
Prerequisites assumed: you can open a Windows command prompt and a Linux shell, you know basic file paths, and you know what a file extension is. The previous chapter covered how to recognize script types by extension. This chapter reads the contents of those scripts.
Comments: notes the interpreter ignores
A comment is text in a script that the interpreter skips. Comments explain what the script does and why. They also let you disable a line temporarily without deleting it.
Each language marks comments differently. The A+ Core 2 exam often shows a short script and asks you to identify the language or the comment line.
| Script type | Extension | Comment marker | Example |
|---|---|---|---|
| Windows batch | .bat | `REM` (also `::` in practice) | `REM Map the drive` |
| PowerShell | .ps1 | `#` for one line, `<# ... #>` for a block | `# List services` |
| Linux shell (Bash) | .sh | `#` | `# Back up files` |
| Python | .py | `#` | `# Count the checks` |
| JavaScript | .js | `//` for one line, `/* ... */` for a block | `// Show a message` |
A comment marker only works at the point where it appears. In Bash, PowerShell and Python, everything after # on that line is ignored. A comment can follow code on the same line, as in count = 3 # integer.
The shebang is a special comment
The first line of a Linux shell script is often #!/bin/bash. It starts with #, so it looks like a comment. The operating system reads it before the shell does. This line is called a shebang, and it names the interpreter that should run the file. If you remove it, the script may run under a different shell.
Good and bad comments
A comment should say why, not repeat what the code already says.
#!/bin/bash
# Bad: set x to 5
x=5
# Good: the backup server allows at most 5 simultaneous copies
max_copies=5Comments also document who wrote a script and when it changed. In a support team, the next technician who opens the file may not know why a step exists.
Variables: named storage for values
A variable is a named place in memory that holds a value. You give the value a name once, then use the name wherever you need the value. If the value changes, you edit one line instead of many.
For example, a script that copies files to /mnt/backup in five places breaks five times if the backup location moves. A variable named dest fixes it in one edit.
Assigning and reading variables in each language
The syntax for assigning a value and for reading it back differs across languages. This difference is the most common source of mistakes.
| Language | Assign | Read |
|---|---|---|
| Batch | `set name=workstation01` | `%name%` |
| PowerShell | `$name = "workstation01"` | `$name` |
| Bash | `name="workstation01"` | `$name` |
| Python | `name = "workstation01"` | `name` |
Notice three things in the table:
- Bash does not allow spaces around
=. Writingname = "x"makes Bash treatnameas a command. - PowerShell variables always start with
$, both when you assign and when you read. - Python variables have no symbol. You write the bare name.
A worked example in Bash
The following script from the topic uses variables and a comment on each key step.
#!/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"Here is how it works, line by line:
srcanddestare variables that you create. They hold two paths.$HOMEand$USERare variables that the system already created. These are environment variables, covered in the next chapter.$srcand$destread the stored paths back.fis the loop variable. On each pass of the loop, it holds one file name.
The double quotes around "$f" and "$dest" matter. If a file is named Quarterly Report.txt, the space would split it into two words without quotes. The cp command would then look for two files named Quarterly and Report.txt.
A worked example in PowerShell
# List stopped services
$stopped = Get-Service | Where-Object { $_.Status -eq 'Stopped' }
foreach ($svc in $stopped) {
Write-Output $svc.Name
}The variable $stopped stores the output of a command, a whole list of service objects. The loop variable $svc holds one service at a time. $_ is a built-in variable that means "the current item" inside the Where-Object filter.
A worked example in batch
@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.
)This script does not create a variable. It reads %ERRORLEVEL%, which is a variable that Windows sets to the exit code of the last command. Zero usually means success. Any other number means an error. The REM line is a comment, and @echo off stops the console from printing each command as it runs.
Variable scope and lifetime
A variable exists only for a limited time and in a limited place. Three cases are worth knowing at this level:
- Script lifetime. A variable you create in a script normally disappears when the script ends. In Bash, a script runs in a child process, so it cannot change the variables of the shell that started it.
- Local to a session. In a batch file,
setchanges the variable for the current command prompt window. Closing the window discards it. - Persistent. Saving a value so that it survives a restart requires a different mechanism, such as the system environment variable settings or a file. Plain assignment does not do this.
Naming rules and conventions
Pick names that describe the content. dest is clearer than d, and backup_dest is clearer still.
- Use letters, digits and underscores. Do not start a name with a digit.
- Bash and Python names are case-sensitive, so
Nameandnameare two different variables. Batch and PowerShell variable names are not case-sensitive. - Avoid names that match commands or keywords, such as
iforfor.
Common errors
These mistakes appear again and again in support scripts and in exam questions.
| Symptom | Likely cause | Fix |
|---|---|---|
| Bash says `name: command not found` | Spaces around `=` | Write `name="value"` |
| Variable prints as empty | Wrong read syntax, or a typo in the name | Check `%name%` in batch and `$name` in Bash and PowerShell |
| Command fails on file names with spaces | Missing quotes around the variable | Write `"$f"` |
| Comment text runs as code | Wrong comment marker for the language | Use `REM`, `#` or `//` as the language requires |
| Variable is gone after the script ends | Scope limited to the script | Use an environment variable or write it to a file |
Using variables safely
A variable can hold input from a user, a file or a network source. If you pass that value straight into a command, an attacker can place extra commands in it. Check what a variable holds before you use it in a command that deletes, copies or changes settings. The risks chapter returns to this.
How to recognize these on the exam
Exam questions usually show a short script and ask one of three things. Use these checks:
- Which language is this? Look for the comment marker and the variable symbol.
REMand%name%point to batch.$name =withforeachpoints to PowerShell. A#!/bin/bashfirst line points to a Linux shell script.importand no$point to Python. - What does the variable hold? Follow the assignment, then follow each read.
- What goes wrong? Look for a missing quote, a space around
=, or the wrong read syntax.
Summary
- A comment is ignored by the interpreter. The marker depends on the language:
REM,#or//. - A variable gives a name to a value so you can reuse and change it in one place.
- Assignment and reading syntax differ by language, and these differences cause most beginner errors.
- Quote variables that may contain spaces, and keep secrets out of scripts.
Exercise
A Linux script contains the line dest = "/mnt/backup" and fails with "dest: command not found". What is wrong, and what is the corrected line?
Show answer
Bash does not allow spaces around the equals sign in an assignment, so it treats dest as a command name. The corrected line is dest="/mnt/backup".
Exercise
A script file starts with @echo off, then REM Map the drive, then net use Z: \\fileserver\shared. Which language is it, which line is a comment, and how would you read a variable named drive in this language?
Show answer
It is a Windows batch script (.bat). The line REM Map the drive is the comment. You read the variable with percent signs, as %drive%.
Exercise
A PowerShell script runs $stopped = Get-Service | Where-Object { $_.Status -eq 'Stopped' }. What does $stopped hold, and what does $_ mean?
Show answer
$stopped holds the list of service objects whose status is Stopped. $_ is the built-in variable for the current item that is being tested by the filter.