A script is a text file of commands. When you notice that you are typing the same five commands every day, that is a script waiting to be written. Scripts are the glue of DevOps: they back up folders, check that services are alive, prepare servers and run inside pipelines. Bash is the shell on almost every Linux server, so a small amount of Bash goes a long way. This lesson teaches the pieces you need and gives you three working scripts.
Why do we need it?
Servers need the same small jobs again and again: backups, checks, clean-ups. A script does them the same way every time, and can run when you are asleep. Scripts are also the glue of pipelines.
A real-life example
Writing a recipe down means anyone can cook the dish the same way. A script is a recipe for the computer. If you do not write it down, every cook does it a little differently and sometimes forgets the salt.
The first line and the safety line
#!/usr/bin/env bash
set -euo pipefail
#!/usr/bin/env bashtells the system which program should run the file.set -estops the script when a command fails, instead of carrying on and doing damage.set -utreats an unset variable as an error, which catches typos.set -o pipefailmakes a pipeline fail if any part of it fails.
Save the file, for example as hello.sh, make it executable with chmod +x hello.sh and run it with ./hello.sh.
Variables, arguments and quotes
NAME="devops"
echo "Hello, $NAME"
SRC="${1:?give a source folder}" # first argument, or stop with this message
KEEP="${3:-7}" # third argument, default 7
TODAY=$(date +%F) # capture the output of a command
echo "Backup for $TODAY"
There must be no spaces around the equals sign when you set a variable. Put variables inside double quotes, as in "$NAME", so that file names with spaces do not break your script. $1, $2 are the arguments and $# is how many there are. $? is the exit code of the last command: 0 means success and anything else means failure.
Tests and loops
if [ -d "$SRC" ]; then
echo "folder exists"
elif [ -f "$SRC" ]; then
echo "it is a file"
else
echo "not found" >&2 # send the message to the error stream
exit 2
fi
for f in *.log; do
echo "checking $f"
done
while read -r line; do
echo "line: $line"
done < sample.log
-dtests for a folder,-ffor a file,-rfor readable,-zfor an empty text, and-eq,-ltand-gecompare numbers.- Use
&&to run the next command only if the first succeeded, and||to run it only if it failed. - A function groups steps:
backup() { ... }, then call it by name.
Script 1: a backup with a retention rule
This script packs a folder into a dated .tar.gz and deletes the oldest backups beyond a number you choose. It was run in the course lab with four backups in a row and a limit of two, and it created four files and removed the two oldest. The script in this lesson was run on Linux in the course lab (bash 5, Python 3.13). The output shown is real. Your numbers (memory, disk, dates) will be different.
#!/usr/bin/env bash
# backup.sh - tar a folder into a dated file and keep only the newest N backups.
# Usage: ./backup.sh <source_dir> <backup_dir> [keep]
set -euo pipefail
SRC="${1:?source dir}"; DEST="${2:?backup dir}"; KEEP="${3:-7}"
[ -d "$SRC" ] || { echo "no such folder: $SRC" >&2; exit 2; }
mkdir -p "$DEST"
STAMP=$(date +%Y%m%d-%H%M%S)
FILE="$DEST/$(basename "$SRC")-$STAMP.tar.gz"
tar -czf "$FILE" -C "$(dirname "$SRC")" "$(basename "$SRC")"
echo "created $(basename "$FILE")"
# delete the oldest ones beyond $KEEP (names sort by date)
ls -1 "$DEST"/*.tar.gz | sort | head -n -"$KEEP" | while read -r old; do
rm -- "$old"; echo "removed $(basename "$old")"
done
$ ./backup.sh /srv/site /srv/backups 2
created site-20261112-022321.tar.gz
created site-20261112-022322.tar.gz
created site-20261112-022323.tar.gz
removed site-20261112-022321.tar.gz
created site-20261112-022324.tar.gz
removed site-20261112-022322.tar.gz
Script 2: summarise a log
This script counts log lines by level, shows which service has the most errors and prints the most common error messages, using awk, grep, sort and uniq. Here it runs on a small sample file. The log lines are made up.
#!/usr/bin/env bash
# logwatch.sh - summarise a log file. Usage: ./logwatch.sh sample.log
set -euo pipefail
FILE="${1:?usage: logwatch.sh <logfile>}"
[ -r "$FILE" ] || { echo "cannot read $FILE" >&2; exit 2; }
echo "Lines by level:"
awk '{print $3}' "$FILE" | sort | uniq -c | sort -rn
echo
echo "Errors by service:"
grep ' ERROR ' "$FILE" | awk '{print $4}' | sort | uniq -c | sort -rn
echo
echo "Most common error text:"
grep ' ERROR ' "$FILE" | sed 's/^.*ERROR [a-z]* *//' | sort | uniq -c | sort -rn | head -3
Lines by level:
4 INFO
3 ERROR
1 WARN
Errors by service:
2 api
1 worker
Most common error text:
1 email failed: connection refused
1 GET /jobs/99 500 database timeout
1 GET /jobs/12 500 database timeout
Script 3: a health check you can reuse
This script checks that a TCP port accepts connections and that a web address answers with code 200. It exits with 0 when healthy and 1 when not, so a scheduler or pipeline can act on the result. In the lab it was tested against a small local web server: it printed OK for the home page, FAIL with 404 for a missing page, and FAIL when the server was stopped.
#!/usr/bin/env bash
# healthcheck.sh - is a TCP port open, and does a URL answer 200? Exit code 0 = healthy.
# Usage: ./healthcheck.sh <host> <port> [path]
set -uo pipefail
HOST="${1:?host}"; PORT="${2:?port}"; PATH_="${3:-/}"
if ! (exec 3<>"/dev/tcp/$HOST/$PORT") 2>/dev/null; then
echo "FAIL: $HOST:$PORT is not accepting connections"; exit 1
fi
CODE=$(curl -s -o /dev/null -m 3 -w '%{http_code}' "http://$HOST:$PORT$PATH_" || true)
if [ "$CODE" = "200" ]; then
echo "OK: $HOST:$PORT$PATH_ answered 200"; exit 0
fi
echo "FAIL: $HOST:$PORT$PATH_ answered ${CODE:-nothing}"; exit 1
$ ./healthcheck.sh 127.0.0.1 8765 /
OK: 127.0.0.1:8765/ answered 200
$ ./healthcheck.sh 127.0.0.1 8765 /missing
FAIL: 127.0.0.1:8765/missing answered 404
$ ./healthcheck.sh 127.0.0.1 8765 # server stopped
FAIL: 127.0.0.1:8765 is not accepting connections
Good habits
- Test scripts on copies of data, not on the real thing. Run
bash -n script.shto check the syntax without running it, andbash -x script.shto see each command as it runs. - Never put passwords in a script. Read them from the environment or a protected file.
- Make scripts safe to run twice (idempotent), because schedulers and people run things again.
- Write a usage line at the top, and print clear messages. Future you will not remember.
Architecture diagram
Here is the idea as a simple picture. You can use the same diagram in your own notes.
flowchart LR
T[Trigger: cron or pipeline] --> S[Script starts]
S --> W[Does the work]
W --> E{Exit code}
E -->|0| OK[Success: continue]
E -->|not 0| F[Fail: stop and alert]
How to check it worked
- Your scripts stop with a clear message when an argument is missing.
bash -nreports no syntax errors for each script.- You restored a backup into a different folder and the files match.
How companies use it
Teams use Bash for backups, health checks, deployment helpers, log clean-up and pipeline steps. Larger logic moves to Python, but Bash stays the fastest way to join Linux commands.
Common errors and how to fix them
- Script works by hand but not in cron. Use full paths and set the PATH. Redirect output to a log to see errors.
- unbound variable. A variable name is misspelled or unset.
set -uhelped you find it. - Spaces in file names break the script. Quote every variable:
"$FILE". - Syntax error near unexpected token. Check missing
then,fiordone, and runbash -n script.sh. - Permission denied.
chmod +x script.sh, and check the first line points at bash.
Best practices
- Start with
set -euo pipefail. - Quote variables.
- Print clear messages and use exit codes.
- Never put passwords in scripts.
- Test on copies and make scripts safe to run twice.
Interview questions with simple answers
- What is a shebang? The first line that tells the system which program runs the file, for example
#!/usr/bin/env bash. - What does `set -e` do? Stops the script on the first failed command.
- How do you read the exit code? With
$?right after the command. - What does `$1` mean? The first argument passed to the script.
- How do you make a variable with a default?
${VAR:-default}. - `&&` vs `||`?
&&runs the next command if the first succeeded.||runs it if the first failed. - How do you loop over files?
for f in *.log; do ...; done. - How do you debug a script?
bash -x script.shshows each command as it runs. - Why quote variables? To stop spaces and special characters from splitting the value.
- Bash or Python? Bash for short Linux glue, Python for larger logic and data.
Practical exercises
Try each one yourself before you look at the hint. Struggling for a few minutes is how the skill sticks.
- Write a script that greets a name given as an argument and stops with a message if none is given. Hint:
${1:?message}. - Write a loop that prints each
.logfile and its line count. Hint:for,wc -l. - Change the backup script to keep five backups. Hint: The third argument.
- Write a script that returns exit 1 if a folder does not exist. Hint:
[ -d "$DIR" ]. - Extend the log script to print the busiest minute. Hint:
awkandcut.
Mini project: Nightly maintenance script
Combine backup, log summary and a health check into one script that runs every night from cron and writes to a log. Test it by breaking each part on purpose and confirming the exit code changes.
Knowledge test
Answer the ten questions in the quiz at the end of this lesson. You pass with 60 percent. If an answer is wrong, read the explanation, then reread the part of the lesson it points to.