What you'll learn
- Start every script with a safe template
- Answer log questions with pipelines of grep, awk, sort and uniq
- Quote variables and use tests and loops correctly
- Debug scripts with bash -x and shellcheck
- Avoid injection, temp-file and secret-handling mistakes
Each lesson is tagged Junior, Mid or Expert, so you can start where you are. Finish with the lab and the quiz; a score of 4 out of 5 marks the course complete in this browser.
The lessons below are in English for now, because they quote technical names, commands and log fields. An Arabic version is planned.
Course map
Each module moves from fundamentals to applied work to an expert challenge. Exercises have worked solutions: try first, then open the solution. 10 modules · 22 exercises · ~3.7 hours
- 0Start here: the shell, setup and the course projectJuniorMidExpert20 min · 1 exercises
- 1Files and folders: navigating and organisingJuniorMidExpert25 min · 2 exercises
- 2Reading and finding filesJuniorMidExpert20 min · 2 exercises
- 3Searching with grep and regular expressionsJuniorMidExpert20 min · 2 exercises
- 4Redirection, pipes and text-processing toolsJuniorMidExpert30 min · 4 exercises
- 5Variables, quoting and expansionJuniorMidExpert20 min · 2 exercises
- 6Scripts: arguments, decisions, loops and functionsJuniorMidExpert30 min · 4 exercises
- 7Robust scripts: exit codes, strict mode, options and debuggingJuniorMidExpert25 min · 2 exercises
- 8Processes and schedulingJuniorMidExpert15 min · 1 exercises
- 9Cheat sheet, assessment and expert challengesJuniorMidExpert15 min · 2 exercises
No prior experience is needed. Module 0 covers the architecture, installation and configuration, and sets up the project you extend in every module. Each command is labelled with its impact (read-only, changes files, changes the system, uses the network). Work on a computer or virtual machine you control.
Start here: the shell, setup and the course project
Goal: Understand what a shell does, install Bash, read a command line confidently, find help, and prepare the project.
The shell and the command line
A shell is the program that interprets the commands you type in a terminal and asks the operating system to run them. Bash (Bourne Again SHell) is the default shell on most Linux distributions and the one you will meet on servers, containers, cloud instances and CI runners.
Linux servers are typically administered over SSH, where the shell is the only interface. Commands are also composable and scriptable: the steps you type during an investigation can be saved as a script and rerun identically on one machine or a thousand, which is the basis of operations automation and incident-response tooling.
Bash reads a line, expands it (variables, wildcards, ~), splits it into words, and starts the program named by the first word with the rest as its arguments. The program writes results and errors back to the terminal and returns an exit status: 0 for success, anything else for failure.
Quick check: Which component turns ls *.log into ls access.log auth.log before ls runs?
Wildcard expansion is done by the shell; ls only ever sees the expanded file names.
| Symptom | Likely cause | Fix |
|---|---|---|
| 'command not found' | the program is not installed or the name is misspelled | check spelling; commands are case-sensitive: LS is not ls |
| nothing happens after Enter | the command is still running or waiting for input | press Ctrl+C to stop it |
Install Bash and open a terminal
You need a terminal window with Bash 4 or newer. Linux has it already; Windows and macOS need one small step.
Every example in this course is typed into Bash. A consistent setup means your output matches the output shown in each lesson.
Install the Windows Subsystem for Linux (WSL), which runs a real Ubuntu Linux inside Windows:
wsl --installRestart when asked, open Ubuntu from the Start menu, and create a Linux user name and password. That window is your Bash terminal.
Open Terminal (Applications → Utilities). macOS uses zsh by default and ships an old Bash 3.2. Install a current Bash with Homebrew, then start it:
brew install bash
bashmacOS tools are BSD versions; a few options differ from Linux (GNU). The lessons note it where it matters.
Bash is already installed. Open the Terminal application (Ctrl+Alt+T on Ubuntu).
bash --versionShow which Bash version is running.Read-onlybash --versionbash --version | head -n 1GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
A version of 4 or higher means you are ready. (| head -n 1 keeps only the first line; module 4 explains it.)
| Symptom | Likely cause | Fix |
|---|---|---|
wsl --install fails | virtualization disabled or an old Windows build | enable virtualization in the firmware settings; update Windows |
| macOS shows version 3.2 | the old system Bash runs first | run bash after installing with Homebrew |
Reading a command line
Every command line has the same parts: the prompt (printed by Bash), the command (a program), options (how it should work, usually starting with -) and arguments (what it should work on).
Documentation, tutorials and colleagues' notes are written in this form. Recognising the parts lets you read unfamiliar commands, look up the right option and spot mistakes before you press Enter.
Short options can be combined (-i -c is the same as -ic); long options use two dashes (--count). Text containing spaces must be quoted so it stays one argument.
~ is your home folder. Relative paths start here.# instead means you are root (administrator): be careful.rana@laptop:~/bash-lab$ grep -i -c 'failed password' logs/auth.log
5-i ignore case, -c count matching lines.Quick check: In ls -l -h /var/log, which part is an argument?
/var/log is what ls works on; -l and -h are options.
Getting help
Every command documents itself. man command opens its manual page, command --help prints a summary, help documents Bash's own built-in commands, and type tells you what a name refers to.
No one memorises every option. Professionals look options up in seconds; the manual on the machine also matches the exact version installed there.
type / help / --helpFind out what a command is and how to use it.Read-onlytype name · help builtin · command --help · man commandtype | builtin, program (with its path), alias or function |
man | full manual; / searches, n next match, q quits |
--help | short summary for most programs |
type cd grep
grep --help | head -n 2cd is a shell builtin grep is /usr/bin/grep Usage: grep [OPTION]... PATTERNS [FILE]... Search for PATTERNS in each FILE.
In man, the SYNOPSIS section shows the syntax: square brackets mark optional parts, ... means 'one or more'.
| Notation in manuals | Meaning |
|---|---|
[OPTION]... | zero or more options, optional |
FILE... | one or more files |
-n, --lines=NUM | short and long form of the same option, taking a number |
a | b | either a or b |
Exercise 1Junior
Find out whether echo is a builtin or a program, and print the first line of wc --help.
Worked solution
type echo
wc --help | head -n 1echo is a shell builtin Usage: wc [OPTION]... [FILE]...
The course project: a log-triage toolkit
Throughout the course you will build a small toolkit for Rimal Logistics, a fictional company. Its servers' logs show login attempts and web requests; your job is to find attacks quickly and report them.
Each module applies its commands to the same project, so you see how they combine and finish with a working triage tool rather than isolated examples.
Each module ends with a Project step. Step 0 creates the course folder and two sample logs. Paste the block into your terminal; by module 4 you will understand every part of it.
mkdir -p ~/bash-lab/logs && cd ~/bash-lab
cat > logs/auth.log <<'LOG'
Dec 3 08:01:12 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec 3 08:01:15 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec 3 08:02:40 web01 sshd[1210]: Accepted publickey for deploy from 198.51.100.7 port 40022 ssh2
Dec 3 08:05:03 web01 sshd[1222]: Failed password for invalid user admin from 192.0.2.44 port 61001 ssh2
Dec 3 08:05:09 web01 sshd[1222]: Failed password for invalid user oracle from 192.0.2.44 port 61001 ssh2
Dec 3 08:07:30 web01 sudo: deploy : TTY=pts/0 ; PWD=/home/deploy ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx
Dec 3 08:09:51 web01 sshd[1240]: Failed password for root from 203.0.113.5 port 52190 ssh2
Dec 3 08:12:02 web01 sshd[1251]: Accepted password for rana from 198.51.100.23 port 50311 ssh2
LOG
cat > logs/access.log <<'LOG'
198.51.100.7 - - [03/Dec/2026:08:00:01 +0300] "GET / HTTP/1.1" 200 5120
203.0.113.5 - - [03/Dec/2026:08:00:03 +0300] "GET /wp-login.php HTTP/1.1" 404 162
203.0.113.5 - - [03/Dec/2026:08:00:04 +0300] "GET /.env HTTP/1.1" 404 162
198.51.100.23 - - [03/Dec/2026:08:01:10 +0300] "POST /api/login HTTP/1.1" 200 88
192.0.2.44 - - [03/Dec/2026:08:02:00 +0300] "GET /admin HTTP/1.1" 403 199
198.51.100.7 - - [03/Dec/2026:08:02:30 +0300] "GET /api/orders HTTP/1.1" 500 47
198.51.100.7 - - [03/Dec/2026:08:02:31 +0300] "GET /api/orders HTTP/1.1" 500 47
LOG
printf 'web01\nweb02\ndb01\n' > hosts.txt
echo "lab ready"; lslab ready hosts.txt logs
ls logs lists access.log and auth.log. Run every later example from ~/bash-lab (cd ~/bash-lab).
| Symptom | Likely cause | Fix |
|---|---|---|
> prompts appear and nothing finishes | the paste was cut off before a closing LOG line | press Ctrl+C, then paste the whole block again |
| 'No such file or directory' | you are in a different folder | run cd ~/bash-lab first |
Files and folders: navigating and organising
Goal: Know where you are, move through the file system, read a long listing, and create, copy, move and delete files safely.
Free account Create a free account or sign in to continue this course.
Reading and finding files
Goal: Look inside text files of any size, understand the structure of a log line, and find files by name, age and size.
Free account Create a free account or sign in to continue this course.
Searching with grep and regular expressions
Goal: Find the lines that matter, count them, and describe what you are looking for with patterns.
Free account Create a free account or sign in to continue this course.
Redirection, pipes and text-processing tools
Goal: Send output to files and into other commands, and turn raw logs into reports with sort, uniq, cut, awk and sed.
Free account Create a free account or sign in to continue this course.
Variables, quoting and expansion
Goal: Store values, reuse command output, calculate, and quote correctly so spaces never break a command.
Free account Create a free account or sign in to continue this course.
Scripts: arguments, decisions, loops and functions
Goal: Save commands in an executable script that takes arguments, decides, repeats and reuses logic.
Free account Create a free account or sign in to continue this course.
Robust scripts: exit codes, strict mode, options and debugging
Goal: Make scripts fail safely, accept options like real tools, and find bugs quickly.
Free account Create a free account or sign in to continue this course.
Processes and scheduling
Goal: See what is running, stop runaway commands, run jobs in the background, and schedule the toolkit.
Free account Create a free account or sign in to continue this course.
Cheat sheet, assessment and expert challenges
Goal: Consolidate the syntax on one page, then apply the course to a new log on your own.
Free account Create a free account or sign in to continue this course.
Quick reference (the cheat-sheet lessons and the PDF content)
Every script starts like this
#!/usr/bin/env bash
set -Eeuo pipefail # stop on errors, unset vars, failed pipes
IFS=$'\n\t' # safer word splitting
trap 'echo "error on line $LINENO" >&2' ERR
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
usage() { echo "usage: $0 [-v] <logfile>" >&2; exit 2; }
verbose=0
while getopts ":v" opt; do
case $opt in v) verbose=1 ;; *) usage ;; esac
done; shift $((OPTIND-1))
[[ $# -eq 1 ]] || usage
log="$1"; [[ -r $log ]] || { echo "cannot read $log" >&2; exit 1; }
main() { (( verbose )) && echo "reading $log" >&2; wc -l < "$log"; }
main "$@"What each line buys you
-eexit on the first failing command-uunset variables are errors, not empty strings-o pipefaila pipe fails if any part fails-EERR trap works inside functionstrap ... EXITcleans up temp files on any exitgetoptshandles flags consistently- Exit codes: 0 ok, 1 error, 2 usage
Pipelines: the Unix superpower
Small tools joined by pipes answer most log questions in one line.
Text processing toolkit
| Tool | Job | Example |
|---|---|---|
grep -E | Filter lines by regex | grep -Ei 'error|fail' app.log |
awk | Pick fields, sum, condition | awk '$9>=500 {c[$7]++} END{for(u in c) print c[u],u}' access.log |
sed | Substitute or delete | sed -E 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g' |
cut / tr | Columns, characters | cut -d: -f1 /etc/passwd |
sort | uniq -c | Count unique values | sort | uniq -c | sort -rn | head |
jq | Query JSON | jq -r '.items[] | select(.sev=="high") | .id' |
find | Files by time, size, perms | find / -xdev -perm -4000 -type f 2>/dev/null |
xargs | Run a command per item | find . -name '*.log' -print0 | xargs -0 gzip |
Variables and quoting: the rules that prevent bugs
| Write | Because |
|---|---|
"$var" | Always quote: spaces and globs break unquoted vars |
"${arr[@]}" | Each element stays one argument |
${var:-default} | Default when empty or unset |
${var:?msg} | Fail with a message when missing |
$(cmd) | Command substitution; avoid backticks |
$(( a + b )) | Integer arithmetic |
local x | Keep function variables local |
String operations
${f%.log}strip suffix${f##*/}basename${s/old/new}replace first${#s}length${s,,}lower case${s:0:8}substring
Tests, conditions and loops
[[ -f $f ]] # regular file exists
[[ -d $d ]] # directory
[[ -z $s ]] # empty string
[[ $a == "$b" ]] # string equal
[[ $s =~ ^[0-9]+$ ]] # regex match
(( n > 10 )) # numeric test
cmd && ok || fail # beware: fail also runs if ok fails# lines of a file (keeps spaces, no subshell)
while IFS= read -r line; do
printf '%s\n' "$line"
done < hosts.txt
for f in /var/log/*.log; do
[[ -e $f ]] || continue # no match
gzip -k -- "$f"
done
for i in {1..5}; do ping -c1 "10.0.0.$i"; doneDecide: Bash or something else?
Rules of thumb
- Bash is glue: start processes, move files, chain tools
- Complex parsing, JSON or retries? Use Python
- Shared by a team? Add
shellcheckand tests (bats) - POSIX
shonly when the target lacks Bash (Alpine: ash)
Ops one-liners worth memorizing
| Question | Command |
|---|---|
| What is listening? | ss -tulpn |
| Who logged in recently? | last -aiw | head; journalctl _COMM=sshd --since today |
| Biggest directories | du -xh / --max-depth=2 2>/dev/null | sort -h | tail |
| Files changed in the last day | find /etc -xdev -mtime -1 -type f |
| Top CPU processes | ps -eo pid,user,%cpu,cmd --sort=-%cpu | head |
| Failed services | systemctl --failed |
| HTTP status of a list of URLs | xargs -n1 curl -s -o /dev/null -w '%{http_code} %{url}\n' < urls |
| Watch a log for a pattern | tail -F app.log | grep --line-buffered ERROR |
Debugging a script
Tools
bash -n script.shsyntax check onlybash -x script.shtrace every commandPS4='+${BASH_SOURCE}:${LINENO}: 'trace with line numbersshellcheck script.shcatches quoting and logic bugsset -x…set +xtrace one block
Classic bugs
- Unquoted
$varsplits on spaces cd dir; rm -rf *when cd fails: usecd dir || exit- Piping into
whileruns in a subshell: variables are lost for f in $(ls): use a glob instead- Windows line endings:
sed -i 's/\r$//'
Secure scripting
| Risk | Do this |
|---|---|
Secrets in scripts or ps output | Read from a file with 0600 permissions or a secret manager; never pass on the command line |
| Predictable temp files | mktemp and an EXIT trap |
Injection through eval or bash -c "$input" | Never eval input; use arrays for commands: cmd=(rsync -a "$src" "$dst"); "${cmd[@]}" |
Untrusted filenames starting with - | End options with --: rm -- "$f" |
curl | bash installers | Download, verify the checksum or signature, read, then run |
| PATH hijack in cron or sudo | Set PATH explicitly at the top; use absolute paths for sensitive commands |
| World-writable script | chmod 750, owned by root if run by root |
shellcheck in CI on every *.sh file. It finds most of the bugs in this course automatically.Key terms
- set -euo pipefail
- Stops a script on errors, unset variables and failed pipeline stages.
- Pipeline
- Commands joined with | so the output of one becomes the input of the next.
- Exit code
- 0 means success; any other number is a failure the caller can test.
- trap
- Runs a command when the script exits or receives a signal, for clean-up.
- Word splitting
- Bash splits unquoted variables on spaces, which breaks filenames: quote them.
- shellcheck
- A linter that finds quoting, logic and portability bugs in shell scripts.
Hands-on lab
Free account Create a free account or sign in to continue this course.
Knowledge check
Answer all five questions, then check your answers. Each answer comes with a short explanation.
Further reading
- GNU Bash manual gnu.org
- ShellCheck shellcheck.net
- Google Shell Style Guide google.github.io
Put it into practice
Use these ThreatAI tools to apply what you learned to your own environment.