Shell scripting, step by step: everything is a command line.
Command lines saved in a file, and the bits of programming bash added on top of them: variables, conditions, loops and functions. Every script runs in a debugger, line by line, the way the slides show it.
13 chapters · 63 pages≈ 212 minscript debugger · script lab with missions · IFS and pattern simulators
Your progress
Start with shell scripts.
Follow the chapters in order or pick one on the map.
From a file of commands to functions and parameters.
Current chapterDone
AI
Study material generated with AI (Claude) from the slides of ISO lecture 08, to be reviewed by the lecturers. It may contain mistakes; for the exam, the reference is the lecture and its slides. Found a mistake? Open an issue on the course repository.
About this material
How it was made
Text, figures and the simulators were generated with Claude (Anthropic) from the slides of lecture 08 – Shell Scripting, following the structure of the interactive lectures 02, 03 and 07. The debuggers are the step-by-step runs of the slides; the script lab runs scripts in a small bash interpreter written for this page.
What was checked
The interpreter of the script lab was tested on every script and terminal session of the slides (outputs, exit codes, error messages, IFS splitting, read, $(...), $(( )), bc, expr, test and [, case, loops, functions, "$@"). It is a teaching model, not bash: only the commands of the lecture exist, and there are no real processes.
Mistakes
If you find one, open an issue with the page and the sentence. Version: November 2026.
Sources and contributors
Slides: USO Team, Copyright (C) 2026 Wyliodrin & Politehnica Bucharest, CC-BY-SA 4.0. Bibliography: the sources listed in the slides of the lecture.
A script automates what you would type: backups, building a project, renaming 300 files. Every line of it is still a command line: words, separated by spaces. Remembering this explains almost every mistake of this lecture.
or you save them in a file, and bash runs them for you
the shell was made to run commands: read a line, split it into words, run the command
a shell script is a file with command lines; the shell runs them one after another
variables, conditions, loops and functions were added on top: everything is still a command line
$_ Ask: what command runs here?
[ $a -lt $b ] is the command [:
[2-lt3]
✅ Great for gluing commands
mkdir → cp → echo
❌ Bad for heavy computation
Integers only, slow. Use Python, C, Rust, ... for that.
#!, #, ; and \
Script syntax
A script is a text file: one command line after another, run from top to bottom.
backup.sh
#!/bin/bash# backup.sh - back up the notesmkdir -p ~/backup
cd ~/backup; lscp ~/notes.txt \
~/backup/
Part
What it is
#!/bin/bash
the shebang: the program that runs the file; for bash it is just a comment
# ...
a comment, until the end of the line
one line
one command line
;
several commands on the same line
\ at the end
the command line goes on, on the next line
Running a script
./backup.sh or bash backup.sh
./backup.sh asks the kernel to run the file: it needs x and reads #!. bash backup.sh runs bash, which only reads the file.
$chmod +x backup.sh # once: the execute permission$./backup.shbacking updone$bash backup.sh # no x neededbacking updone
Common mistake
backup.sh instead of ./backup.sh
Without a /, the shell searches the name in PATH, and the current folder is not in PATH: bash: backup.sh: command not found.
Instead: write the path, ./backup.sh, or run bash backup.sh.
#!/usr/bin/python3, #!/usr/bin/env node
The shebang, for any language
The kernel runs the program written after #!, with the file as its parameter. The same chmod +x and ./name work for any language.
#!/usr/bin/python3
name = "alice"print(f"Hello, {name}!")
$./hello.pyHello, alice!
the kernel runs /usr/bin/python3./hello.py
#!/usr/bin/env nodeconst name = "alice";
console.log(`Hello, ${name}!`);
$./hello.jsHello, alice!
the kernel runs /usr/bin/envnode./hello.js
/usr/bin/env node
env searches node in PATH: useful when you do not know where it is installed.
$_
You do not need to know the language of a script: ./backup.sh, ./hello.py and ./hello.js all run the same way.
Check yourself
notes.sh has no x permission. Which command still runs it?
Shell scripts
Cheat sheet and practice
Write
Means
#!/bin/bash
the first line: the program that runs the file
# text
a comment
cmd1; cmd2
two commands on one line
cmd \
the line goes on below
chmod +x s.sh, ./s.sh
run the file: the kernel reads #!
bash s.sh
run bash, the script is its parameter
Variable syntax
Define, use, change, delete, export
NAME=value stores the text, $NAME puts it back in a command line. No spaces around =.
Replaced when the line runs
A variable holds text, not a formula
The shell replaces $namewhen the line runs. greeting keeps the text it got then, not the recipe.
No spaces around =
Wrong definitions: a space splits the line
A line starts with a command. A NAME=value word before it is a variable only for that command.
Variables
Cheat sheet and practice
Write
Means
name="alice"
define or change, no spaces around =
$name, "$name"
the value takes its place
${name}_notes
the name ends at }
unset name
delete: it is empty after
export name
put it in the environment of the child processes
name=value cmd
a variable only for cmd
Internal Field Separator
IFS: where the shell cuts
IFS is a variable of the shell; its characters are the separators. By default: space, tab and newline. The shell uses it to cut an unquoted$NAME (and, later, the line that read reads).
$printf'%q\n'"$IFS"$' \t\n'
printf '%q' shows the invisible characters: a space, \t (tab), \n (newline).
IFS = spacetabnewline
Splitting a variable
An unquoted $x is cut at IFS
Before running printf '[%s]\n' $x, the shell does three things:
replace: $x becomes its value, Alice Smith:20
cut: the value is cut at the characters of IFS (by default: space, tab, newline); every piece becomes a separate word
printf '[%s]\n' prints every word it gets between [ ], one per line. echo also gets 2 words and prints them with one space: the 3 spaces are lost.
Two kinds of separators
The characters of IFS do not all cut the same way. Space, tab and newline are the exception: they are blanks, and the shell treats them gently.
In IFS
Several in a row
At the start or the end
Example
space, tab, newline (the blanks)
one cut: a b → ab
dropped: ␣␣a␣b␣␣ → ab
IFS default, x=" a b " → [a][b]
any other character, e.g. :,
every one cuts: a::b → a""b, an empty word in the middle
at the start: an empty first word, :a → ""a; at the end: nothing, a: → a
IFS=:, x="a b::c" → [a b][][c]
A blank that is not in IFS is a normal character: with IFS=:, the space in a b does not cut, a b stays one word.
Many spaces are one cut
Spaces are special
The two kinds of separators in one script: first the blanks (many in a row are one cut, the ends are dropped), then : (every one cuts, :: makes an empty word).
Quoting and IFS
Quotes keep one word
IFS cuts an unquoted value. Quoted, "$x" is always one word, whatever IFS is, with its spaces.
$_
Quotes say "one word": write "$NAME" in quotes, unless you want it cut.
Check yourself
x="a b". How many words does printf '[%s]' "$x" get after the format?
Words and IFS
Cheat sheet and practice
Write
The words
$x
the value, cut at the characters of IFS
"$x"
the value, one word, the spaces kept
IFS=:
now only : cuts, for the whole script
unset IFS
back to space, tab, newline
printf'[%s]\n'$x
shows every word between [ ]
printf'%q\n'"$IFS"
shows the invisible characters
read syntax
read: one line from stdin into variables
read is a built-in of the shell: it waits for a line (until Enter) and puts it in variables.
Write
Means
read NAME
waits for a line, puts the whole line in NAME
read -p "Your name: " NAME
-p: writes a prompt (a question) first
read first last
several names: the line is cut at IFS, one word for every variable, the last one takes the rest
read -r line
-r, raw: keeps the \ characters as they are
read -s password
-s, silent: does not show what the user types
read has an exit code too
0 if it read a line, 1 at the end of the input (Ctrl + D): while read (in Loops) stops on it.
Fields separated by :
IFS=: read: IFS only for this read
NAME=value before a command is a variable only for that command: after read, IFS is back to space, tab, newline.
$head-n 1 /etc/passwdroot:x:0:0:root:/root:/bin/bash$IFS=: read user x uid rest < /etc/passwd$echo"$user has UID $uid"root has UID 0$echo"$rest"0:root:/root:/bin/bash
🐞 read
The script waits for the keyboard
-r, IFS=, and pipes
The pitfalls of read
By default, read does not give you the line exactly as it is in the file. It changes it in two ways, and each one has its own fix:
The line in the file
read l gives
Why
The fix
C:\new\temp
C:newtemp
\ is an escape for read: it removes it
-r (raw): keep the \
two spaces
two spaces
the spaces at the start and at the end are in IFS: read cuts them
IFS= (empty), only for this read: nothing is cut
Both fixes together read a line exactly as it is: IFS= read -r line. A third trap is not about the text: after a |, read runs in a copy of the shell and its variables are lost.
(( expression )) – a command that computes: the C operators, ( ), variables without$
=, +=, -=, ++, -- change a variable
$(( expression )) – like $( command ), but the shell computes and puts the result in its place, as text
anywhere in a command line, also inside "..."
⚠️ Integers only!
$((7 / 2)) is 3: no 3.5, no 0.5. (( )) as a command, ++ and -- exist only in bash (and zsh).
One parenthesis runs a command, two compute
$( ) or $(( ))?
command substitution
$echo $(a+b)bash: a+b: command not found
a copy of bash runs a+b: it is not a program, it prints nothing; then the shell runs echo
arithmetic
$echo $((a+b))5
inside (( )), a is the value of a; the shell computes 2 + 3, no program starts; then it runs echo5
$_
$(command) – the output of a command; $((expression)) – the result of a computation. With the program expr, they agree: $(expr $a + $b) ≡ $((a+b)) → 5.
The shell builds the text, bc computes
Decimals with bc
bc is a calculator program: it reads the expression from stdin and prints the result. The shell only builds the text of the expression.
$echo"7 / 2"|bc # scale=0: no decimals3$echo"scale=2; 7 / 2"|bc # 2 decimals3.50$echo"7 / 2"|bc-l # -l: scale=20 and the math functions3.50000000000000000000$echo"sqrt(2)"|bc-l1.41421356237309504880
scale is the number of decimals bc keeps after a division; it starts at 0. Set it in the text you send (scale=2;), or start bc -l: scale=20, plus s(), c(), a(), l(), e() (sine, cosine, arctangent, logarithm, exponential).
Check yourself
What does echo $((10 / 4)) print?
The C operators, on integers
The operators of (( ))
Operators
Meaning
Example
+ - * /
add, subtract, multiply, divide
$((7 / 2)) → 3
%**
remainder, power (bash)
$((2 ** 10)) → 1024
< <= > >= == !=
compare: 1 true, 0 false
$((3 > 2)) → 1
&& || !
and, or, not
$((1 && 0)) → 0
& | ^ ~ << >>
bits
$((1 << 4)) → 16
= += -= ++ --
change a variable (bash)
((x += 2))
c ? a : b
a if c is true, else b
$((5 > 3 ? 10 : 20)) → 10
( )
group
$(( (2 + 3) * 4 )) → 20
Arithmetic
Cheat sheet and practice
Write
Means
$a+$b
just text: 2+3
$(expr$a + $b)
the program expr computes; \* for multiply
$((a + b))
the shell computes, the result as text
((n++)), ((x += 2))
a command that changes a variable
$((7 / 2))
3: integers only
$(echo"3.5 * 2" | bc)
decimals: the program bc
echo"scale=2; 7 / 2" | bc, bc -l
decimals after a division: 3.50
The condition is a command
if runs a command
The condition of if is not an expression, it is a command: if runs it and looks at its exit code.
if command; then
commands
elif other_command; then
commands
else
commands
fi
if runs the command and looks at its exit code
then – the commands that run if it ended with 0 (true)
elif – another command to try, optional, as many as needed
else – when no command ended with 0, optional
fi – if backwards, the end
⚠️ In the shell, 0 is true!
0true – success, then runs
1false – a warning or an error (1 … 255)
the opposite of C, where 0 is false
The same, on one line
A ; takes the place of the newline before then, elif, else and fi.
if command; then commands; else commands; fi
$ifgrep -q kiwi fruits.txt; thenecho"we have kiwi"; fiwe have kiwi
🐞 if
The exit code chooses the branch
-lt, -eq, -f …
test and [: commands that compare
test checks a condition and only sets its exit code. < and > are redirects, so the comparisons are options.
Test
True (0) if
N -eq M, -ne
the numbers are equal, not equal
N -lt M, -le
less than, less or equal
N -gt M, -ge
greater than, greater or equal
S = T, S != T
the texts are equal, different
-z S, -n S
the text is empty, not empty
-e F, -f F, -d F
F exists, is a file, is a directory
! E, E -a E, E -o E
not, and, or
$a=2; b=3$test $a -lt $b; echo $?0$test $a -gt $b; echo $?1$type-a [[ is a shell builtin[ is /usr/bin/[$[ $a -lt $b ]; echo $?0
the shell sees [2-lt3]: [ is test, and ] is just its last parameter
The first command that ends with 0 wins
if, elif, else
[ only sees words
The pitfalls of [
$_
The shell splits the line into words before[ starts; [ cannot know what you meant: spaces everywhere, and quote the variables, "$x".
Real syntax for conditions, added later
[[ ]] and (( ))
$if [[ $a -lt $b ]]; then echo "smaller";fismaller$if (( a < b )); then echo "smaller";fismaller
[[ ... ]] – like [, but a keyword of bash: no word splitting, $x may be empty
(( ... )) – the C-like math of $(( )), as a condition: not 0 is true
$_
Finally a C-like condition: the shell does not split (( )) into words, so < is not a redirect there. Both exist only in bash (and zsh).
Check yourself
Which line prints yes when a=7 and b=10?
Conditions
Cheat sheet and practice
Write
Means
if cmd; then ...; fi
then runs if cmd ends with 0
elif cmd; then, else
the next try, the rest
["$a" -lt "$b" ]
the program [: spaces everywhere, ] last
[ -f f ], [ -d d ], [ -z "$x" ]
a file, a folder, an empty text
[[$a -lt $b ]]
bash: no splitting
(( a < b ))
bash: C-like, on integers
case syntax
case: the condition is a word
case WORD in
pattern1)
commands
;;
pattern2|pattern3)
commands
;;
*)
commands
;;
esac
case takes the text of WORD and compares it with every pattern, top to bottom
pattern) – the commands that run if WORD matches it; ;; – the end of the branch, jump after esac
| – or: any of the patterns
* matches anything: the default branch, always last, optional
esac – case backwards, the end
The same, on one line
No newline is needed: the branches end with ;;.
case WORD in pattern) commands ;; pattern) commands ;; esac
The patterns of case are globs, like ls *.txt, but they match the text of the word: case never looks at the disk.
Common mistake
Globs are not regular expressions
In a glob, . is a dot and * is any text; in a regex (grep, lecture 6), . is any character and * repeats it. n.* as a glob does not match notes.txt – no dot after n; as a regex it does.
Instead: in case, write n* for "starts with n".
case
Cheat sheet and practice
Pattern
Matches
apple
exactly apple
a*
a, then any text
*.txt
any text ending in .txt
???
exactly three characters
[yY]*
y or Y, then any text
apple|kiwi
either (only in case)
*
anything: the default, last
Repeat while a command ends with 0
while and until
while command; do
commands
doneuntil command; do
commands
done
while runs the command before every round and looks at its exit code
do – the body, runs while the command ends with 0
done – jump back to the command
until – the opposite: repeat while the command does not end with 0
inside the body: break leaves the loop, continue goes to the next round
The same, on one line
A ; takes the place of the newline before do and before done.
< file after done is the stdin of the whole loop: every read takes the next line; at the end of the file read ends with 1 and the loop stops.
The loop only runs a command
The pitfalls of while
while
Cheat sheet and practice
Write
Means
while cmd; do ...; done
repeat while cmd ends with 0
until cmd; do ...; done
repeat while it does not
whileread l; do ...; done < f
the lines of a file, in the shell itself
whileIFS=, read a b
the fields of a CSV
break, continue
leave the loop, the next round
for syntax
for: once for every word
for NAME in word1 word2 word3; do
commands
donefor f in *.txt; do ...; donefor w in$(cat fruits.txt); do ...; donefor i in {1..5}; do ...; done
the variable NAME takes every word after in, one by one
do – the body, runs once for every word, with $NAME the word
done – go back and take the next word
the words can come from a glob, from the output of a command, or from brace expansion (bash)
The same, on one line
A ; takes the place of the newline before do and before done.
for NAME in word1 word2; do commands; done
$for f in apple kiwi; doecho"I like $f"; doneI like appleI like kiwi
🐞 for
Once for every word
seq, {1..10..3}, for (( ))
Counting with a step
$for i in $(seq 1 3 10); do echo -n"$i ";done; echo1 4 7 10$n=5; for i in $(seq 1 $n); do echo -n"$i ";done; echo1 2 3 4 5
seq first step last – a program that prints the numbers; it works with variables: seq runs after the shell replaced them
{1..10..3} (bash) – the shell writes them, but not with variables: {1..$n} stays as it is
for ((i = 1; i <= 10; i += 3)); do ...; done (bash) – a C-like for
Choose where the list is cut
IFS and for
The list of for is cut at the characters of IFS, like any unquoted text. for is a keyword, not a command: IFS=: for ... is a syntax error. Set IFSbefore the loop and unset it after.
$line="apple:kiwi:cherry"$for f in $line; do echo "[$f]";done[apple:kiwi:cherry]$IFS=: for f in $line; do echo "[$f]";donebash: syntax error near unexpected token `do'
$(...), "$(...)" or while read
for goes over words, not lines
for
Cheat sheet and practice
Write
The words of the list
for f in a b c
the words you wrote
for f in *.txt
the file names
for w in$(cmd)
the output, cut at IFS
for i in$(seq1310)
14710
for i in {1..5}
12345 (bash, no variables)
for ((i = 0; i < 3; i++))
C-like (bash)
Function syntax
A function is a new command
greet() {
localwho="$1"echo"Hello, $who!"return0
}
greet alice
$greet aliceHello, alice!$greetHello, !
name() { – the start, the () are always empty
the parameters, the words after the name in the call: $1 is the first one, $2 the second, ...; $# is how many there are
local – a variable only for the function
return N – leave the function with the exit codeN, like exit for a script
} – the end: the function is now defined
call it like any command: the name, then the words; a missing parameter is just empty
$_
A function is called exactly like a program: the command name, then the words – so it gets its parameters the same way a script does. Define it before calling it.
🐞 Functions
Parameters, exit code, local
A command prints, and ends with an exit code
Output or exit code
A function, like any command, has two ways to answer: the output (text, the data) and the exit code (success or error). The data is printed and captured with $(...); return N is not the data.
the data: echo it, the caller captures it, sum=$(add 2 3); success or error: return N
It prints and ends with an exit code, nothing more
Function pitfalls
Functions
Cheat sheet and practice
Write
Means
name() { ...; }
define a command, before calling it
name a b
call it: $1, $2, $#, "$@" inside
localx=1
a variable only for the function
return N
leave with the exit code N (0 – 255)
echo result + r=$(name)
give back data: print it, capture it
name && ..., if name; then
use its exit code
Parameter syntax
$0, $1, $2, ..., $#
The words of the command line become variables of the script.
$./params.sh alice "Alice Smith" bob
./params.sh$0
alice$1
Alice Smith$2
bob$3
$# = 3
Variable
Value
$0
the name of the script, as you typed it
$1, $2, ... ${10}
the parameters
$#
how many parameters: 3
"$@"
all the parameters, every one a separate word
$_
The parameters are the words your shell made from the command line: the quotes keep Alice Smith one word.
Going over the parameters
"$@" keeps the words
"$@" is every parameter, each one a separate word. Without quotes, $@ is text, cut again at IFS – the same rule as for any variable.
show.sh
#!/bin/bashfor p in"$@"; doecho"[$p]"done
$./show.sh"Alice Smith" bob[Alice Smith][bob]
show2.sh
#!/bin/bashfor p in$@; doecho"[$p]"done
$./show2.sh"Alice Smith" bob[Alice][Smith][bob]
Check yourself
./s.sh "a b" c – what is $#?
Script parameters
Cheat sheet and practice
Write
Means
$0
the name of the script
$1 ... $9, ${10}
the parameters
$#
how many
"$@"
all of them, every one a word
shift
drop $1, the others move down
exit1
stop the script with an error
Quick recap
The ideas, in short
One idea per card; the title is the idea, the text says why it matters in practice. Recap shows all the cards, Flashcard one at a time.
01 · Scripts
Everything is a command line
click / Space
01 · Scripts
Everything is a command line
Variables, if, loops were added on top of a shell that runs commands: ask what command runs here?