Sign in Start free

EngineeringFree course

Bash Scripting

Automate Linux safely: a strict script template, pipelines that answer questions fast, quoting rules, loops, debugging and secure scripting.

  • Level Junior → Mid
  • Time 220 min
  • Modules 10
  • Exercises 22 with worked solutions
  • Includes Lab, 5-question quiz, references

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

  1. 0Start here: the shell, setup and the course projectJuniorMidExpert20 min · 1 exercises
  2. 1Files and folders: navigating and organisingJuniorMidExpert25 min · 2 exercises
  3. 2Reading and finding filesJuniorMidExpert20 min · 2 exercises
  4. 3Searching with grep and regular expressionsJuniorMidExpert20 min · 2 exercises
  5. 4Redirection, pipes and text-processing toolsJuniorMidExpert30 min · 4 exercises
  6. 5Variables, quoting and expansionJuniorMidExpert20 min · 2 exercises
  7. 6Scripts: arguments, decisions, loops and functionsJuniorMidExpert30 min · 4 exercises
  8. 7Robust scripts: exit codes, strict mode, options and debuggingJuniorMidExpert25 min · 2 exercises
  9. 8Processes and schedulingJuniorMidExpert15 min · 1 exercises
  10. 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.

0

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.

20 min

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.

Userlocal terminal or SSH sessionTerminal emulatorWindows Terminal, GNOME Terminal, iTerm2Shell (Bash)parses the line, expands variables and wildcards, starts programsLinux kernelprocesses, permissions, file systems, network (via system calls)Hardwaredisk, CPU, network cardstdout / stderrand exit statuscommandline
Bashwhat you will learnNavigate and manage filespaths, cd, ls, wildcardsmkdir, cp, mv, rm, findRead and searchcat, less, head, tail, wcgrep and regular expressionsPipes and text tools> >> 2> | redirectionsort, uniq, cut, awk, sedVariables and expansion$var, $( ), $(( ))quoting, ${var:-default}Scriptsshebang, chmod, argumentsif, for, while, case, functionsProduction habitsexit codes, strict mode, getoptsdebugging, processes, cron

Quick check: Which component turns ls *.log into ls access.log auth.log before ls runs?

SymptomLikely causeFix
'command not found'the program is not installed or the name is misspelledcheck spelling; commands are case-sensitive: LS is not ls
nothing happens after Enterthe command is still running or waiting for inputpress 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:

PowerShell (as administrator)
wsl --install

Restart when asked, open Ubuntu from the Start menu, and create a Linux user name and password. That window is your Bash terminal.

bash --versionShow which Bash version is running.Read-only
Syntaxbash --version
Example
shell
bash --version | head -n 1
Output
Expected output
GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
Verify

A version of 4 or higher means you are ready. (| head -n 1 keeps only the first line; module 4 explains it.)

SymptomLikely causeFix
wsl --install failsvirtualization disabled or an old Windows buildenable virtualization in the firmware settings; update Windows
macOS shows version 3.2the old system Bash runs firstrun 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.

1
User and host. Who you are logged in as, and on which machine. Check it before running commands on a server.
2
Current folder. ~ is your home folder. Relative paths start here.
3
$ means 'ready'. A # instead means you are root (administrator): be careful.
8
Output. Printed by grep: five matching lines.
terminal
rana@laptop:~/bash-lab$ grep -i -c 'failed password' logs/auth.log
5
4
Command. The program to run.
5
Options. -i ignore case, -c count matching lines.
6
Argument: the pattern. Quoted so the space does not split it into two words.
7
Argument: the file. A relative path from the current folder.

Quick check: In ls -l -h /var/log, which part is an argument?

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-only
Syntaxtype name · help builtin · command --help · man command
Parameters
typebuiltin, program (with its path), alias or function
manfull manual; / searches, n next match, q quits
--helpshort summary for most programs
Example
shell
type cd grep
grep --help | head -n 2
Output
Expected output
cd is a shell builtin
grep is /usr/bin/grep
Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
Verify

In man, the SYNOPSIS section shows the syntax: square brackets mark optional parts, ... means 'one or more'.

Notation in manualsMeaning
[OPTION]...zero or more options, optional
FILE...one or more files
-n, --lines=NUMshort and long form of the same option, taking a number
a | beither 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
shell
type echo
wc --help | head -n 1
Output
echo 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.

Steps 1-2folders, first lookSteps 3-4search, attack reportStep 5variables, dated reportStep 6triage.sh v1Step 7robust triage.sh v2Step 8schedule, monitor
shell · project step 0: create the lab (paste once)
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"; ls
Expected output
lab ready
hosts.txt  logs

ls logs lists access.log and auth.log. Run every later example from ~/bash-lab (cd ~/bash-lab).

SymptomLikely causeFix
> prompts appear and nothing finishesthe paste was cut off before a closing LOG linepress Ctrl+C, then paste the whole block again
'No such file or directory'you are in a different folderrun cd ~/bash-lab first
1

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.

25 min

Free account Create a free account or sign in to continue this course.

2

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.

20 min

Free account Create a free account or sign in to continue this course.

3

Searching with grep and regular expressions

Goal: Find the lines that matter, count them, and describe what you are looking for with patterns.

20 min

Free account Create a free account or sign in to continue this course.

4

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.

30 min

Free account Create a free account or sign in to continue this course.

5

Variables, quoting and expansion

Goal: Store values, reuse command output, calculate, and quote correctly so spaces never break a command.

20 min

Free account Create a free account or sign in to continue this course.

6

Scripts: arguments, decisions, loops and functions

Goal: Save commands in an executable script that takes arguments, decides, repeats and reuses logic.

30 min

Free account Create a free account or sign in to continue this course.

7

Robust scripts: exit codes, strict mode, options and debugging

Goal: Make scripts fail safely, accept options like real tools, and find bugs quickly.

25 min

Free account Create a free account or sign in to continue this course.

8

Processes and scheduling

Goal: See what is running, stop runaway commands, run jobs in the background, and schedule the toolkit.

15 min

Free account Create a free account or sign in to continue this course.

9

Cheat sheet, assessment and expert challenges

Goal: Consolidate the syntax on one page, then apply the course to a new log on your own.

15 min

Free account Create a free account or sign in to continue this course.

Quick reference (the cheat-sheet lessons and the PDF content)
1

Every script starts like this

JuniorMid
bash · template.sh
#!/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

  • -e exit on the first failing command
  • -u unset variables are errors, not empty strings
  • -o pipefail a pipe fails if any part fails
  • -E ERR trap works inside functions
  • trap ... EXIT cleans up temp files on any exit
  • getopts handles flags consistently
  • Exit codes: 0 ok, 1 error, 2 usage
2

Pipelines: the Unix superpower

Junior

Small tools joined by pipes answer most log questions in one line.

cat / journalctlread|grep -Efilter|awk / cutextract|sortorder|uniq -ccount|sort -rn | headrankstdin → each command transforms the stream → stdout (stderr goes its own way: 2>errors.log)grep 'Failed password' /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head
3

Text processing toolkit

JuniorMid
ToolJobExample
grep -EFilter lines by regexgrep -Ei 'error|fail' app.log
awkPick fields, sum, conditionawk '$9>=500 {c[$7]++} END{for(u in c) print c[u],u}' access.log
sedSubstitute or deletesed -E 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g'
cut / trColumns, characterscut -d: -f1 /etc/passwd
sort | uniq -cCount unique valuessort | uniq -c | sort -rn | head
jqQuery JSONjq -r '.items[] | select(.sev=="high") | .id'
findFiles by time, size, permsfind / -xdev -perm -4000 -type f 2>/dev/null
xargsRun a command per itemfind . -name '*.log' -print0 | xargs -0 gzip
4

Variables and quoting: the rules that prevent bugs

Junior
WriteBecause
"$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 xKeep 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
5

Tests, conditions and loops

JuniorMid
bash · conditions
[[ -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
bash · loops
# 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"; done
6

Decide: Bash or something else?

Mid
Under ~100 lines?Mostly runs commands?Python or Godata structures, APIs, testsBashglue, ops, CI stepsPythonparsing, JSON, logicnoyesyesno

Rules of thumb

  • Bash is glue: start processes, move files, chain tools
  • Complex parsing, JSON or retries? Use Python
  • Shared by a team? Add shellcheck and tests (bats)
  • POSIX sh only when the target lacks Bash (Alpine: ash)
7

Ops one-liners worth memorizing

JuniorMid
QuestionCommand
What is listening?ss -tulpn
Who logged in recently?last -aiw | head; journalctl _COMM=sshd --since today
Biggest directoriesdu -xh / --max-depth=2 2>/dev/null | sort -h | tail
Files changed in the last dayfind /etc -xdev -mtime -1 -type f
Top CPU processesps -eo pid,user,%cpu,cmd --sort=-%cpu | head
Failed servicessystemctl --failed
HTTP status of a list of URLsxargs -n1 curl -s -o /dev/null -w '%{http_code} %{url}\n' < urls
Watch a log for a patterntail -F app.log | grep --line-buffered ERROR
8

Debugging a script

Mid

Tools

  • bash -n script.sh syntax check only
  • bash -x script.sh trace every command
  • PS4='+${BASH_SOURCE}:${LINENO}: ' trace with line numbers
  • shellcheck script.sh catches quoting and logic bugs
  • set -x … set +x trace one block

Classic bugs

  • Unquoted $var splits on spaces
  • cd dir; rm -rf * when cd fails: use cd dir || exit
  • Piping into while runs in a subshell: variables are lost
  • for f in $(ls): use a glob instead
  • Windows line endings: sed -i 's/\r$//'
9

Secure scripting

MidExpert
RiskDo this
Secrets in scripts or ps outputRead from a file with 0600 permissions or a secret manager; never pass on the command line
Predictable temp filesmktemp 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 installersDownload, verify the checksum or signature, read, then run
PATH hijack in cron or sudoSet PATH explicitly at the top; use absolute paths for sensitive commands
World-writable scriptchmod 750, owned by root if run by root
Habit Run 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.

1What does set -o pipefail change?
2Why write "$file" instead of $file?
3Safest way to create a temporary file:
4Which counts unique values, most frequent first?
5A script needs JSON parsing, retries and data structures. Best choice?

Further reading

Put it into practice

Use these ThreatAI tools to apply what you learned to your own environment.