Shell Scripting — Easy Exam Guide Unit u06 (bash). The exam almost always asks you to WRITE a bash script (~5 points). This guide gives you the tools and the recurring patterns. 🔴 = comes a lot.
Written in simple (B1) English. Read it from top to bottom before the exam.
0How "shell" comes in the exam
In almost every exam (24 of 25 papers) there is one task: write a bash script, worth about 5 points. Sometimes there is also a small "what does this script print?" question. So the main skill is writing scripts — and the tasks reuse the same few patterns (see §7).
| The question you will see | How often | Section |
|---|---|---|
🔴 "Write a bash script that …" (parse a file, count words/lines, find + filter + rename, read ls -l/ps) | almost every exam (~5 pts) | all of §1–§7 |
🟡 "What does this script print?" (positional parameters, shift, source) | sometimes | §3 |
⚠️ The exam loses points on syntax
Three small rules cause most mistakes: no spaces around =, spaces inside [ ], and a ; before then on one line. Learn these now (§2, §4, §5).1Script basics 🔴
- First line is the shebang:
#!/bin/bash— it says which interpreter to use. It must be the very first line. #starts a comment. One command per line, or use;on the same line.- Run a script two ways:
./script.sh args— needs execute permission (chmod +x); runs in a sub-shell (changes are lost after).source script.sh args(or. script.sh) — runs in the current shell; no execute permission needed; anexitinside will close your terminal.
- Exit status: in the shell 0 = success/true, non-zero = error/false (the opposite of C). Check the last command with
$?. End withexit 0.
2Variables & quoting 🔴
name="value" # set (NO spaces around =)
echo $name # use
echo ${name}Paul # braces keep the name clear from following text
- Everything is a string (even numbers). To do math you need special syntax — see §6.
- Single quotes
'...'= no expansion ($xstays literal). Double quotes"..."= variables expand. Use double quotes when the value has spaces.
✗ Top syntax trap
name = value is WRONG (spaces). It must be name=value. With spaces, bash thinks name is a command.3Command-line parameters 🔴
| Symbol | Meaning |
|---|---|
$0 | the script name (not counted as an argument) |
$1 $2 … | argument 1, 2, … |
$# | the number of arguments |
$@ / $* | all the arguments. Use "$@" to keep each argument separate (best for loops). |
$? | exit status of the last command |
$$ | the PID of the script |
shift | drop $1; old $2 becomes $1, and $# goes down by 1 |
🎯 In the exam — script trace (2021-09-07 Ex5, 2024-02-27 Ex9)
Count the arguments for $#. Remember: single quotes keep $0 literal; shift removes the first argument; if the script is run with source, an exit closes the terminal and no execute permission is needed.Almost every script starts by checking the arguments:
if [ $# -lt 1 ]; then
echo "USAGE: $0 <file>"
exit 1
fi
4The test command: [ ] 🔴
[ condition ] checks something and gives an exit status. You must put spaces inside the brackets.
| Type | Operators |
|---|---|
| Numbers | -eq -ne -lt -le -gt -ge |
| Strings | = (equal) · != · -z s (empty) · -n s (not empty) |
| Files | -e exists · -f regular file · -d directory · -r/-w/-x readable/writable/executable · -L symlink · -s not empty |
| Logic | -a (and), -o (or), ! (not) inside [ ]; or && / || between two tests |
✗ Traps
[$a -eq 1]is WRONG — need spaces:[ $a -eq 1 ].- Use numbers operators for numbers (
-eq), strings operators for text (=). Mixing them fails. - Always quote variables in tests:
[ "$x" = "abc" ](so an empty$xdoes not break the test).
5if / for / while + reading a file 🔴
if [ cond ]; then ... elif [ cond ]; then ... else ... fi for x in 1 2 3; do echo $x; done # a fixed list for f in $(ls *.txt); do echo $f; done # a command's output for ((i=0;i<n;i++)); do echo $i; done # C-style while [ cond ]; do ... done case $x in a) echo A ;; *) echo other ;; esac
Reading a file line by line (very common)
while read line
do
echo "$line"
done < input.txt
✗ Trap
Put the < input.txt at the done, not after read. And on one line, write if [ … ]; then (the ; is needed).6Substitution, arithmetic, functions, arrays 🔴
- Command substitution — capture a command's output:
d=$(date),n=$(cat f | wc -l). - Arithmetic — plain
=stores text, so use one of:let s=a+b,s=$((a+b)), or((s=a+b)). - Functions:
name(){ commands; }; inside,$1 $2 …are the function's arguments;return nsets the status. - Arrays:
a=(x y z); one element${a[0]}; all${a[@]}; count${#a[@]}. (Usedeclare -Afor an associative array, e.g. counting.)
The filter toolbox (used inside scripts)
| Tool | Use |
|---|---|
wc -l / -w / -c | count lines / words / bytes |
cut -d' ' -f2 | take field 2 (delimiter is a space); cut -c1 takes character 1 |
tr -s ' ' | squeeze repeated spaces (do this before cut on command output) |
sort -n / -k2 / -r | sort by number / by field 2 / reverse |
grep -v grep | remove the grep line itself (when searching ps) |
find DIR -name '*.txt' -type f -size +1G | find files recursively by name / type / size |
7The "stock" exam tasks 🔴 learn these patterns
The write-script tasks reuse the same ideas. If you can do these five patterns, you can do almost any of them:
① Read
ls -l fields (permissions, size, owner, symlink target)stats=$(ls -l "$file")
type=$(echo $stats | cut -c1) # -, d, or l
size=$(echo $stats | cut -d" " -f5) # field 5 = size
if [ "$type" = "l" ]; then
target=$(echo $stats | cut -d" " -f11) # after the ->
fi② Count words / lines per line of a file
nlines=$(cat "$1" | wc -l)
while read line; do
nwords=$(echo $line | wc -w)
echo "$nwords $line" >> tmp.txt
done < "$1"
sort -n tmp.txt > "$1"③ Find + filter + act on files
for f in $(find "$DIR" -type f -name "*.txt" -size -1048576c); do
cat "$f" >> small.txt
done④ Get a PID from
ps and kill itpid=$(ps -aux | grep "$cmd" | grep -v grep | tr -s " " | cut -d" " -f2) kill -9 $pid
⑤ Parse a table (skip header, take columns)
readelf -s "$elf" | tr -s " " | tail -n +4 | while read line; do
addr=$(echo $line | cut -d" " -f2)
size=$(echo $line | cut -d" " -f3)
done🎯 In the exam
Real tasks (in the drills): file info from ls -l (2024-02-07), concat/split .txt files (2024-06-20), word/line counts + sort (2025-09-17), parse a calendar (2024-09-18), filter a readelf table (2025-06-12), start/stop programs with ps+kill (2023-02-17).8One-page trap sheet
- Shebang
#!/bin/bashfirst line. Shell exit status: 0 = true. Check with$?. name=value— NO spaces.[ $a -eq 1 ]— spaces inside.if [ … ]; then— semicolon.- Numbers:
-eq -ne -lt -le -gt -ge. Strings:= != -z -n. Files:-e -f -d -r -w -x -L -s. Always quote:[ "$x" = "y" ]. - Params:
$0name,$1…args,$#count,"$@"all (separate),shiftdrops$1. - Math needs
let/$(( ))/(( )). Capture output with$( ). - Read a file:
while read line; do … done < file(redirect atdone). - Field tools:
tr -s ' 'thencut -d' ' -f N; counts withwc -l/-w/-c;sort -n -k;findfor recursion. sourceruns in the current shell (no+xneeded;exitcloses the terminal).