Scripting basics: variables, loops and conditions
Listen to this lesson
Every episode of this course is also a podcast: listen on Spotify.
This episode is a study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.
Why this matters
A task done once by hand is fine. The same task done on forty servers, or every night, or by three different people who each do it slightly differently, is where mistakes come from. Scripts make repeated work fast and, more importantly, identical every time.
Server+ does not expect you to be a programmer. It expects you to recognise the common scripting languages, understand the basic building blocks well enough to read a short script and say what it does, and know how to run scripts without causing damage. That last part matters most, because a script repeats a mistake as faithfully as it repeats a correct step.
The lesson
Bash, PowerShell, Python and batch, and where each is native
Four scripting languages cover most server work.
- Bash is the standard shell on Linux and macOS. Its scripts usually end in .sh and begin with a shebang line, #!/bin/bash, telling the system which interpreter to run them with. It is ideal for chaining together the command-line tools Linux administration is built on.
- PowerShell is Microsoft's shell and scripting language, native on Windows and also available on Linux. Scripts end in .ps1. Its commands, called cmdlets, follow a verb-noun pattern such as Get-Service or New-ADUser, and it passes objects rather than plain text between commands, which makes filtering and formatting results straightforward.
- Python is a general-purpose language available on almost every platform and installed by default on most Linux distributions. Scripts end in .py. It suits larger or more complex tasks, and working with data or web APIs.
- Batch files, ending in .bat or .cmd, are the older Windows command interpreter's scripts. They are still found running legacy jobs, but new Windows automation is written in PowerShell.
The practical rule is to use the language native to the system being managed, unless a task is complex enough to need Python.
Variables, data types and comments
A variable is a named place to store a value so a script can use it later. The syntax differs between languages:
- In Bash, name=value with no spaces around the equals sign, and $name to use it.
- In PowerShell, variables always start with a dollar sign: $name = "value".
- In Python, name = "value", with no symbol before the name.
- In batch, set name=value, and %name% to use it.
Values have data types. The common ones are strings (text), integers (whole numbers), floating-point numbers (with decimals), Booleans (true or false), and arrays or lists, which hold several values under one name. Types matter because they change behaviour: the string "10" and the number 10 are compared and added differently. Bash treats almost everything as a string; PowerShell and Python track types for you.
Comments are notes for people that the interpreter ignores. Bash, PowerShell and Python use #; batch uses REM or ::. A good comment explains why a step is there, for the next person who reads the script, which is often the same administrator a year later.
Loops and conditionals
Two structures give scripts their power.
A conditional makes a decision: if something is true, do one thing, else do another. A script might check whether a directory exists before writing to it, or whether a service is running before restarting it. Conditions use comparison operators: PowerShell and Bash's test syntax use forms such as -eq (equal), -ne (not equal), -gt (greater than) and -lt (less than), while Python uses ==, !=, > and <.
A loop repeats steps. There are three common kinds:
- A for or foreach loop runs once for each item in a list, such as each server in a list of names or each file in a folder. This is the loop that turns a one-server task into a forty-server task.
- A while loop repeats as long as a condition stays true, such as waiting until a service starts. It needs a way out: a loop whose condition never becomes false runs forever, which is why careful scripts also count attempts or check the time.
- A do-until loop, found in PowerShell, runs at least once and repeats until a condition becomes true.
Combining the two is most of everyday scripting: for each server in a list, if the disk is nearly full, send an alert.
Running a script safely: permissions, execution policy and a lab machine first
A script runs with the permissions of whoever runs it, so a mistake in a script run as an administrator can do an administrator's worth of damage in seconds.
- Permissions. On Linux, a script needs the execute permission, set with chmod +x, before it can be run directly. Run scripts with the least privilege that works, and only use sudo or an elevated prompt when the task needs it.
- Execution policy. PowerShell has an execution policy that controls whether scripts may run. Restricted allows none; RemoteSigned allows local scripts but requires scripts downloaded from the internet to be signed by a trusted publisher; AllSigned requires every script to be signed. It is a safety feature to prevent accidental execution, not a security boundary, but it should not simply be set to Unrestricted to make an error go away.
- Test first. Run new scripts in the lab from the first lesson, or against one non-critical server, before running them everywhere. Many commands have a way to show what they would do without doing it: PowerShell's -WhatIf parameter, or a dry-run option like the ones covered in the migration lesson.
- Be careful with deletion and wildcards. A variable that turns out to be empty can turn a command meant to delete one folder's contents into a command that deletes far more. Check that variables hold what you expect before destructive steps.
Reading someone else's script before running it
Administrators constantly find scripts: in a colleague's folder, in old documentation, or on the internet. Running one without reading it hands control of the server to whoever wrote it.
Before running someone else's script:
- Read every line and make sure you understand what it does. If a line is unclear, find out before running it.
- Look for destructive commands: deletions, formatting, changes to permissions, accounts or firewall rules, and anything that disables security software.
- Look for anything that reaches out: downloads from the internet, commands that run code fetched from a URL, or connections that send data elsewhere. A single line that downloads and runs another script means you are running code you have not read.
- Look for hard-coded values: server names, paths, passwords and addresses that belong to someone else's environment and would do the wrong thing in yours. A password written inside a script is also a security problem in its own right.
- Check the source: prefer scripts from trusted, known sources, and treat anything obfuscated, such as long encoded strings, as a warning sign.
Then test it in the lab like any other script.
Try it
An interactive exercise runs here: a real Linux machine in your browser that checks each step. The commands above work on any Linux machine too.
Practise what you just read
1. An administrator must run the same task on 40 servers listed in a file. Which script structure fits?
Select one
Show answer
B. A for or foreach loop runs its body once for each item in a list, turning a one-server task into a forty-server task with every server treated identically.
2. A downloaded PowerShell script will not run, and the execution policy is RemoteSigned. Why?
Select one
Show answer
D. RemoteSigned allows local scripts but requires scripts marked as downloaded to be signed. The fix is to review the script and unblock or sign it, not to set the policy to Unrestricted.
3. Before running a script found in old documentation, what should an administrator do first?
Select one
Show answer
A. A script runs with its user's full rights. Reading it for destructive commands, downloads and hard-coded values, then testing it in a lab, prevents inheriting someone else's mistakes.
7 more questions on this objective are part of the full course.
Hands-on labs
Part of the free CompTIA Server+ SK0-005 course — 51 lessons and 72 hands-on labs.
This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.