$ bash-scripting-guide
$ cd 03-bash-scripting

Bash Scripting
Guide

From your first #!/bin/bash to traps, arrays, and error handling, nineteen topics, basic to advanced, each with a real script you can run.

# Instructor: Abderrahmane Yahiaoui
Companion to: Introduction To Linux
19topics
3levels
1guide
backup.sh
#!/bin/bash set -euo pipefail today=$(date +%F) for file in *.log; do cp "$file" "backup-$today/" done # basic to advanced, one script at a time
How to use this guide: Work top to bottom the first time through, each level builds on the last. Coming back later? Use the search bar or the tracker above to jump straight to a topic.
Level 1 of 3

Basics

Write a script, give it data, and get data back out. Everything else in this guide builds on these five ideas.

01
Basics

Your First Script

A bash script is just a text file full of commands, saved so you can run them all at once instead of typing them one by one.

hello.sh
#!/bin/bash # My first script echo "Hello, world!"
bash
you@machine:~$ chmod +x hello.sh you@machine:~$ ./hello.sh Hello, world!

The first line is the shebang, it tells the shell which interpreter should run the file. chmod +x marks the file as executable, and the ./ tells bash to look for the script right here instead of in your PATH.

Shortcut: You can also run a script without making it executable at all, with bash hello.sh. It works, but chmod +x plus ./ is the standard, expected way.
02
Basics

Variables

Variables store data so you can reuse it. Set one with name=value, no spaces, and read it back with a $.

vars.sh
#!/bin/bash name="Sara" count=3 echo "Hello, $name, you have $count new alerts"

There can't be any spaces around the =. Wrap values that contain spaces in quotes. $name and ${name} both work, the braces are useful when text follows right after, like ${name}s.

Common mistake: name = "Sara" (with spaces) doesn't set a variable, bash reads it as running a command called name with two arguments, and fails.
03
Basics

Command-Line Arguments

Scripts can accept input right when you run them, the same way cp source dest takes two arguments.

greet.sh
#!/bin/bash echo "Script name: $0" echo "First argument: $1" echo "All arguments: $@" echo "Argument count: $#"
bash
you@machine:~$ ./greet.sh Sara Algeria Script name: ./greet.sh First argument: Sara All arguments: Sara Algeria Argument count: 2

$0 is the script's own name, $1/$2… are the arguments in order, $# is how many were given, and $@ expands to all of them as separate words.

04
Basics

Reading User Input

Sometimes you want the script to ask a question while it's running, instead of taking everything as arguments up front.

ask.sh
#!/bin/bash read -p "What's your name? " name echo "Nice to meet you, $name!"

The -p flag shows a prompt without needing a separate echo first. Whatever the person types gets stored in the variable you name at the end, here, name.

Tip: Add -s (read -sp "Password: " pass) to hide what's typed, handy for passwords or tokens.
05
Basics

Output & Quoting

echo is fine for simple messages; printf gives you real formatting control. Either way, quoting your variables matters more than it looks.

output.sh
#!/bin/bash file="my report.txt" echo "Processing: $file" printf "Name: %s, Count: %d\n" "$file" 3

printf uses format specifiers like %s (string) and %d (number), and, unlike echo, never adds a newline unless you write \n yourself. Keep "$variable" in quotes, especially for filenames that might contain spaces.

Common mistake: Dropping the quotes around $file lets bash split it on every space, so rm $file can quietly try to delete "my" and "report.txt" as two separate files.
Level 2 of 3

Intermediate

Make decisions, repeat work, and start organizing scripts into reusable pieces, conditionals, loops, functions, arrays, and the string and math tools you'll use daily.

06
Intermediate

If / Elif / Else

Conditionals let a script make decisions instead of running the same commands every time.

age.sh
#!/bin/bash age=20 if [ "$age" -ge 18 ]; then echo "You can vote." elif [ "$age" -ge 13 ]; then echo "Teenager." else echo "Child." fi

Every if needs a matching fi to close it. The spaces around [ and ] are required, [ is actually its own command (a shorthand for test), not punctuation.

07
Intermediate

Test Operators & Comparisons

What you can actually put inside those square brackets: numbers, strings, and files each have their own comparison operators.

checks.sh
#!/bin/bash file="notes.txt" if [ -f "$file" ]; then echo "$file exists and is a regular file" fi if [[ "$file" == *.txt ]]; then echo "It's a text file" fi
-eq -ne -gt -lt -ge -le
number comparisons
= != -z -n
string equal / not / empty / not empty
-f -d -e
is a file / directory / exists at all

[[ ]] is a bash upgrade to [ ], it supports pattern matching like *.txt and handles unquoted variables more safely. Prefer it when you're writing bash specifically (not a portable /bin/sh script).

08
Intermediate

Loops: for, while, until

Repeat an action over a list of things, or keep going until some condition changes.

for-loop.sh
#!/bin/bash for i in 1 2 3 4 5; do echo "Count: $i" done for file in *.log; do echo "Found: $file" done
while-loop.sh
count=1 while [ "$count" -le 3 ]; do echo "Attempt $count" count=$((count + 1)) done

for walks through a fixed list (numbers, filenames, arguments). while keeps going as long as its condition is true. until is the mirror image, it keeps going as long as its condition is false.

09
Intermediate

Case Statements

When you're checking one variable against several possible values, case reads more cleanly than a long chain of elif.

fruit.sh
#!/bin/bash read -p "Enter a fruit: " fruit case "$fruit" in apple|pear) echo "That's a pome fruit." ;; banana) echo "That's a berry, botanically!" ;; *) echo "Not sure what that is." ;; esac

The | separates multiple patterns that lead to the same action, *) catches anything that didn't match (like a default case), ;; ends each block, and esac, "case" backwards, closes the whole thing.

10
Intermediate

Functions

Package up logic you'll use more than once, instead of copy-pasting the same lines throughout a script.

greet-fn.sh
#!/bin/bash function greet() { local name="$1" echo "Hello, $name!" } greet "Sara" greet "Yacine"

The function keyword is optional (greet() { ... } works too). local keeps a variable scoped to the function instead of leaking into the rest of the script. Inside a function, $1, $2… refer to its own arguments, not the script's.

Order matters: A function has to be defined before the line that calls it, bash reads top to bottom.
11
Intermediate

Arrays

Store a list of values in a single variable, instead of juggling item1, item2, item3.

arrays.sh
#!/bin/bash tools=("nmap" "wireshark" "burpsuite") echo "First tool: ${tools[0]}" echo "All tools: ${tools[@]}" echo "Total: ${#tools[@]}" for tool in "${tools[@]}"; do echo "- $tool" done

Indexing starts at 0. Always quote "${tools[@]}" when looping, without quotes, entries containing spaces get split apart.

12
Intermediate

String Manipulation

Bash can slice, replace, and reformat text on its own, without reaching for an external tool.

strings.sh
#!/bin/bash path="/home/sara/report.txt" echo "Length: ${#path}" echo "Uppercase: ${path^^}" echo "Replace: ${path/report/summary}" echo "Substring: ${path:6:4}"
${#var}
length
${var^^} ${var,,}
uppercase / lowercase
${var/old/new}
replace first match
${var:start:len}
substring
13
Intermediate

Arithmetic

Bash can do integer math natively, no need for a calculator command for simple counting and totals.

math.sh
#!/bin/bash a=7 b=2 echo "Sum: $((a + b))" echo "Remainder: $((a % b))" ((a++)) echo "a is now $a"

$(( )) evaluates a math expression and only works with whole numbers. For decimals, pipe an expression into a tool like bc.

Level 3 of 3

Advanced

Capture output, feed in whole blocks of text, handle failure on purpose, clean up after yourself, and know how to find a bug when something breaks.

14
Advanced

Command Substitution

Capture the output of a command and store it in a variable, instead of just printing it to the screen.

backup-name.sh
#!/bin/bash today=$(date +%Y-%m-%d) count=$(ls -1 | wc -l) echo "Backup for $today: $count files"

$(command) runs the command and substitutes its output right there. It's preferred over the older backtick syntax, easier to read, and it nests cleanly: $(echo $(date)) works, nested backticks don't.

15
Advanced

Here Documents

Feed several lines of text into a command or a file, without juggling a separate template file.

report.sh
#!/bin/bash cat << EOF > report.txt System report Generated: $(date) Host: $(hostname) EOF

EOF is just a label, pick any word you like. Everything between the two EOF markers is passed through as-is, and $(...) substitutions still run inside it. Quote the opening marker (<< 'EOF') if you want the text kept completely literal, with no substitution at all.

16
Advanced

Exit Codes & Error Handling

Every command reports back whether it succeeded, scripts can check that and react.

check.sh
#!/bin/bash grep "root" /etc/passwd > /dev/null if [ $? -eq 0 ]; then echo "Found it." else echo "Not found." fi exit 0

0 means success, anything else means failure. $? holds the exit code of the last command that ran. exit ends the script early with a code of your choice, useful so other scripts (or CI pipelines) calling this one can tell whether it worked.

short-circuit.sh
mkdir backup && cd backup ping -c1 host || echo "Host unreachable"

&& runs the next command only if the first succeeded; || runs it only if the first failed. Handy one-line shortcuts for simple error handling.

Good habit: Add set -e near the top of a script to make it stop the instant any command fails, instead of plowing ahead with bad data.
17
Advanced

Trap & Cleanup

Run cleanup code automatically, even if the script is interrupted, so temporary files and half-finished work don't pile up.

tempwork.sh
#!/bin/bash tmpfile=$(mktemp) cleanup() { rm -f "$tmpfile" echo "Cleaned up." } trap cleanup EXIT echo "Working with $tmpfile..."

trap cleanup EXIT runs the cleanup function no matter how the script ends, it finished normally, hit an error, or you pressed Ctrl+C.

18
Advanced

Reading Files Line by Line

Process a file's contents one line at a time, the reliable pattern for looping over a list stored in a file.

read-lines.sh
#!/bin/bash while IFS= read -r line; do echo "Line: $line" done < server_list.txt

IFS= stops leading/trailing whitespace from being trimmed, and -r stops backslashes from being treated as escape characters. This exact pattern, while IFS= read -r line; do ... done < file, is the standard, reliable way to read a file in bash.

19
Advanced

Debugging & Best Practices

A handful of habits that turn "why isn't this working" into a five-second fix.

strict.sh
#!/bin/bash set -euo pipefail # -e stop on error, -u error on unset variables, -o pipefail catch pipe failures
bash
you@machine:~$ bash -x myscript.sh + today=2026-07-11 + echo 'Backup for 2026-07-11'

set -euo pipefail near the top of every script is the single highest-value habit here. bash -x script.sh prints every command as it actually runs, with variables already substituted, the fastest way to see what a script is really doing.

Before you ship it: Run your script through shellcheck.net (or the shellcheck CLI). It catches most quoting and logic mistakes before they become 2am debugging sessions.

No topics match your search. Try a different word, like arrays, loops, or trap.