Shell & Bash

Beginner · Roadmap · 60 lessons · 10 groups

Learn the shell and Bash from your first command to scripts that last: streams and pipes, quoting and expansion, functions, traps, processes and jobs, everyday tools, and testing. Sixty lessons, every command run on Bash 5.3.

0%

Not started

Nothing saved yet. Progress is kept in this browser until you sign in.

Start the path

What the shell is · 6

Files and directories · 6

Streams, pipes and text · 8

Quoting and expansion · 6

Scripting basics · 6

Scripting in depth · 7

Processes and jobs · 5

Working interactively · 5

Everyday tools · 6

Writing scripts that last · 5

01What a shell is, and Bash vs ZshA shell reads your commands and starts programs. See how it differs from the terminal, what $SHELL really tells you, and where Bash and Zsh disagree.Beginner · 6 min02Anatomy of a commandA command line is a list of words. See how the shell splits them, who reads options, why -- ends them, and where macOS BSD tools differ from GNU.Beginner · 6 min03Getting help with man, help and typeFind out what a command is with type, read builtin docs with help and external docs with man. Includes why man bash can show the wrong Bash version on a Mac.Beginner · 9 min04Moving around the filesystemUnderstand the working directory, absolute and relative paths, ., .., ~ and cd -, then use pushd and popd to hop between directories without losing your place.Beginner · 6 min05The PATH and how commands are foundSee how the shell finds a command by walking $PATH in order, why ./script needs the dot, how the hash cache hides changes, and how shadowing works.Beginner · 15 min06Startup files and login vs interactive shellsLearn which startup file Bash reads and when: login or not, interactive or not. Each claim was tested with real files, plus the Zsh equivalents.Beginner · 10 min01Listing and inspecting filesRead ls -l column by column, show hidden files, sort by time or size, and inspect files with stat and file, including BSD vs GNU differences on macOS.Beginner · 15 min02Creating, copying, moving and removingUse mkdir, touch, cp, mv, rm and rmdir safely. See which of them silently overwrite, why rm has no undo, and how a trailing slash changes cp -R on macOS.Beginner · 9 min03Permissions and chmodDecode rwx for owner, group and others, set modes with chmod in octal and symbolic form, and learn how directory permissions differ from file permissions.Beginner · 6 min04Hard and symbolic linksA file's name is separate from its data. Hard links share an inode, symlinks store a path, and sed -i can quietly break a hard link.Beginner · 8 min05Globbing and wildcardsThe shell, not the command, expands *, ? and [...] into file names. See hidden files, unmatched patterns and quoting, plus globstar, nullglob and extglob.Beginner · 10 min06Finding files with findSearch a tree by name, type, age and size with find, run commands on matches with -exec, and avoid the quoting and -o traps. BSD vs GNU notes.Beginner · 8 min01stdin, stdout and stderrEvery program starts with three streams: input, output and error, numbered 0, 1 and 2. See why errors skip pipes and how programs detect terminals.Beginner · 9 min02RedirectionPoint stdin, stdout and stderr at files with <, >, >>, 2> and 2>&1. Covers why order matters, how sort file > file destroys data, noclobber, and /dev/null.Beginner · 7 min03Pipes and pipelinesChain commands with | so each one's stdout feeds the next one's stdin. Stages run concurrently, report only the last status, and need pipefail.Beginner · 5 min04Viewing text with cat, less, head and tailRead files with cat, page through them with less, sample the top with head and the end with tail -n, follow growing logs with tail -f, and spot BSD vs GNU gaps.Beginner · 9 min05Searching with grepFilter lines with grep: count, invert, ignore case, print only matches, search trees, and read exit statuses. macOS BSD grep has no -P.Beginner · 20 min06sort, uniq, cut, tr and wcFive small filters that turn raw text into answers: sort by field or number, count duplicates with uniq -c, slice with cut, rewrite with tr, count with wc.Beginner · 8 min07Editing streams with sedUse sed to substitute, delete and print lines as text flows past: s///, addresses, capture groups, in-place edits, and macOS BSD sed differences.Beginner · 15 min08Processing columns with awkSplit lines into fields with awk, filter with conditions, sum and group with arrays, and avoid the header-row and shell-variable traps on BSD awk.Beginner · 20 min01Quoting - single, double and escapesHow Bash decides where one word ends and the next begins, and the three tools that override it: single quotes, double quotes and the backslash.Beginner · 8 min02Variables and the environmentShell variables versus environment variables, how export hands a value to child processes, and the one-shot VAR=value command form.Beginner · 8 min03Parameter expansionUse ${var} forms to supply defaults, trim prefixes and suffixes, replace text, change case and measure length without calling sed, cut or basename.Beginner · 6 min04Brace and tilde expansionGenerate lists and ranges with {a,b} and {1..5}, back up files with file{,.bak}, and know when ~ expands to a home directory and when it stays literal.Beginner · 4 min05Command and arithmetic substitutionCapture a command's output with $(...), do integer math with $((...)), and avoid the pitfalls: stripped newlines, padded wc output, no floats, leading zeros.Beginner · 8 min06Word splitting and the order of expansionThe fixed sequence Bash follows before running a command, why unquoted variables split and glob, and how IFS, set -x and quote removal fit in.Beginner · 22 min01Your first script - shebang and execute bitTurn commands into a reusable script file: the #! line that names the interpreter, the execute permission, and why a script needs ./ to run.Beginner · 12 min02Exit status and && / || listsEvery command ends with a number, 0 for success. Read it with $?, chain commands on it with && and ||, and avoid the A && B || C trap.Beginner · 15 min03Conditionals with if, test and double bracketsHow if decides using an exit status, what [ ] and [[ ]] really are, the common file and string tests, and the string-versus-number traps.Beginner · 8 min04Loops - for, while and untilRepeat work over files, lists, counters and lines of input with for, while and until, and avoid the classic traps of looping over ls output.Beginner · 10 min05Case statementsMatch one value against several glob patterns with case, handle several spellings with |, set a default with *), and know which terminators need Bash 4.Beginner · 16 min06Functions, arguments and scopeName a block of commands with a function, pass it arguments with $1 and $@, return a status or output, and keep variables inside with local.Beginner · 10 min01Parsing options with getoptsGive a script real command-line options with getopts: flags, options with values, error handling, OPTIND and shift, and where getopts stops.Intermediate · 5 min02Reading input and here documentsRead user input and file lines with read -r, split fields with IFS, and feed blocks of text to commands with here documents and here strings.Intermediate · 7 min03Arrays and associative arraysHold lists safely in indexed arrays, count by key with associative arrays, and see why macOS's Bash 3.2 lacks associative arrays and mapfile.Intermediate · 7 min04Strict mode - set -e, -u and pipefailWhat set -e, set -u and set -o pipefail each change, the cases where -e silently does nothing, and why strict mode is a safety net, not a guarantee.Intermediate · 10 min05Traps and cleanupRun cleanup code however a script ends with trap on EXIT and signals, create temp files safely with mktemp, and know what a trap cannot catch.Intermediate · 15 min06Subshells and process substitutionKnow when Bash quietly runs code in a copy of itself, why variables set there vanish, and how <(command) feeds a command's output to tools that want files.Intermediate · 8 min07Debugging with set -x and ShellCheckFind shell script bugs by tracing execution with set -x and a custom PS4, checking syntax with bash -n, and linting with ShellCheck before you run.Intermediate · 15 min01Processes: ps, top and the process treeSee what is running with ps and top, read PID, PPID and STAT columns, walk a process's parents up to PID 1, and spot zombies. macOS flags noted.Beginner · 20 min02Signals and killSignals are how you ask a process to stop, reload or pause. Learn kill, SIGTERM versus SIGKILL, the 128+n exit codes, and pkill. Numbers differ on macOS.Beginner · 5 min03Job control: foreground and backgroundRun a command in the background with &, suspend with Ctrl-Z, resume with bg and fg, and manage jobs by %number using jobs, kill and wait.Beginner · 11 min04Surviving logout: nohup, disown and tmuxWhy closing a terminal kills your background jobs (SIGHUP) and three fixes: nohup before starting, disown after, and tmux to detach a whole session.Intermediate · 9 min05Running things later: cron and atSchedule commands with crontab's five fields and run one-off jobs with at. Why a cron job fails when the same command works at your prompt.Intermediate · 19 min01History and readline shortcutsSearch and reuse past commands with Ctrl-R, !! and !$, edit the line with readline keys, and tune HISTCONTROL so your history stays useful. Tested in Bash 5.3.Beginner · 7 min02Aliases and shell functions in rc filesShorten repeated commands with aliases, use functions when you need arguments, and put both in an rc file. Includes where aliases silently do not work.Beginner · 10 min03Customizing the promptBuild a Bash prompt from PS1 escapes, add colour without breaking line wrapping, show the git branch with a function, and use PROMPT_COMMAND.Beginner · 20 min04Tab completionHow Bash completes commands, paths and variables on Tab, why flags and subcommands only complete with extra scripts, and how to write your own with complete.Intermediate · 3 min05Dotfiles and configuration managementKeep your shell config in a Git repo and install it on any machine: a symlink script, the bare-repo method, and what GNU Stow adds. Mind the secrets.Intermediate · 12 min01Archives with tar and gzipBundle a directory with tar, compress with gzip, list before extracting, and avoid the traps: leading slashes, -C, and macOS zcat. Tested with bsdtar.Intermediate · 8 min02Disk usage with df and duFind out how full a disk is with df and what filled it with du. Covers -h, -s, depth limits, sorting, and the BSD flags that differ on macOS.Intermediate · 20 min03diff and patchCompare files and directories with diff, read unified diffs, share a change as a patch file, apply it with patch -p1, undo it with -R, and handle rejects.Intermediate · 10 min04Fetching with curl and wgetFetch URLs from the shell with curl: quiet mode, saving files, headers, status codes, -f for scripts, redirects. Why a 404 still exits 0. wget compared.Intermediate · 14 min05JSON on the command line with jqRead, filter and reshape JSON in a pipeline with jq: paths, select, map, -r, @csv, --arg, group_by, and the exit codes that tell you a filter found nothing.Intermediate · 17 min06Remote work with ssh, scp and rsyncRun commands on another machine with ssh, copy files with scp, and sync directories with rsync. Trailing slashes, dry runs, --delete, and what I could not test.Intermediate · 11 min01Portability: POSIX sh and BashDecide whether a script targets POSIX sh or Bash, find bashisms with ShellCheck, and see what /bin/sh, dash and the macOS Bash 3.2 each accept. Tested on macOS.Intermediate · 13 min02Structure and style: main functions and shfmtLay out a script with functions and a main, guard it so it can be sourced for tests, and let shfmt and ShellCheck settle formatting. Run on shfmt 3.14.Intermediate · 3 min03Safe temporary files and atomic writesCreate temp files with mktemp instead of guessable names, clean up with a trap, and replace files atomically with write-then-mv. BSD mktemp differences noted.Intermediate · 7 min04Logging, usage messages and exit codesMake a script behave like a real command: usage text, messages on stderr, a small log function, and exit codes that mean something. Run on Bash 5.3.Intermediate · 7 min05Testing scripts with BatsWrite automated tests for shell scripts with Bats: @test blocks, run, status and output, temp dirs, skip, and sourcing functions. Run on bats-core 1.14.Intermediate · 23 min

What the shell is

6 lessons

  1. 01 / 06What a shell is, and Bash vs ZshA shell reads your commands and starts programs. See how it differs from the terminal, what $SHELL really tells you, and where Bash and Zsh disagree.6 min
  2. 02 / 06Anatomy of a commandA command line is a list of words. See how the shell splits them, who reads options, why -- ends them, and where macOS BSD tools differ from GNU.6 min
  3. 03 / 06Getting help with man, help and typeFind out what a command is with type, read builtin docs with help and external docs with man. Includes why man bash can show the wrong Bash version on a Mac.9 min
  4. 04 / 06Moving around the filesystemUnderstand the working directory, absolute and relative paths, ., .., ~ and cd -, then use pushd and popd to hop between directories without losing your place.6 min
  5. 05 / 06The PATH and how commands are foundSee how the shell finds a command by walking $PATH in order, why ./script needs the dot, how the hash cache hides changes, and how shadowing works.15 min
  6. 06 / 06Startup files and login vs interactive shellsLearn which startup file Bash reads and when: login or not, interactive or not. Each claim was tested with real files, plus the Zsh equivalents.10 min

Files and directories

6 lessons

  1. 01 / 06Listing and inspecting filesRead ls -l column by column, show hidden files, sort by time or size, and inspect files with stat and file, including BSD vs GNU differences on macOS.15 min
  2. 02 / 06Creating, copying, moving and removingUse mkdir, touch, cp, mv, rm and rmdir safely. See which of them silently overwrite, why rm has no undo, and how a trailing slash changes cp -R on macOS.9 min
  3. 03 / 06Permissions and chmodDecode rwx for owner, group and others, set modes with chmod in octal and symbolic form, and learn how directory permissions differ from file permissions.6 min
  4. 04 / 06Hard and symbolic linksA file's name is separate from its data. Hard links share an inode, symlinks store a path, and sed -i can quietly break a hard link.8 min
  5. 05 / 06Globbing and wildcardsThe shell, not the command, expands *, ? and [...] into file names. See hidden files, unmatched patterns and quoting, plus globstar, nullglob and extglob.10 min
  6. 06 / 06Finding files with findSearch a tree by name, type, age and size with find, run commands on matches with -exec, and avoid the quoting and -o traps. BSD vs GNU notes.8 min

Streams, pipes and text

8 lessons

  1. 01 / 08stdin, stdout and stderrEvery program starts with three streams: input, output and error, numbered 0, 1 and 2. See why errors skip pipes and how programs detect terminals.9 min
  2. 02 / 08RedirectionPoint stdin, stdout and stderr at files with <, >, >>, 2> and 2>&1. Covers why order matters, how sort file > file destroys data, noclobber, and /dev/null.7 min
  3. 03 / 08Pipes and pipelinesChain commands with | so each one's stdout feeds the next one's stdin. Stages run concurrently, report only the last status, and need pipefail.5 min
  4. 04 / 08Viewing text with cat, less, head and tailRead files with cat, page through them with less, sample the top with head and the end with tail -n, follow growing logs with tail -f, and spot BSD vs GNU gaps.9 min
  5. 05 / 08Searching with grepFilter lines with grep: count, invert, ignore case, print only matches, search trees, and read exit statuses. macOS BSD grep has no -P.20 min
  6. 06 / 08sort, uniq, cut, tr and wcFive small filters that turn raw text into answers: sort by field or number, count duplicates with uniq -c, slice with cut, rewrite with tr, count with wc.8 min
  7. 07 / 08Editing streams with sedUse sed to substitute, delete and print lines as text flows past: s///, addresses, capture groups, in-place edits, and macOS BSD sed differences.15 min
  8. 08 / 08Processing columns with awkSplit lines into fields with awk, filter with conditions, sum and group with arrays, and avoid the header-row and shell-variable traps on BSD awk.20 min

Quoting and expansion

6 lessons

  1. 01 / 06Quoting - single, double and escapesHow Bash decides where one word ends and the next begins, and the three tools that override it: single quotes, double quotes and the backslash.8 min
  2. 02 / 06Variables and the environmentShell variables versus environment variables, how export hands a value to child processes, and the one-shot VAR=value command form.8 min
  3. 03 / 06Parameter expansionUse ${var} forms to supply defaults, trim prefixes and suffixes, replace text, change case and measure length without calling sed, cut or basename.6 min
  4. 04 / 06Brace and tilde expansionGenerate lists and ranges with {a,b} and {1..5}, back up files with file{,.bak}, and know when ~ expands to a home directory and when it stays literal.4 min
  5. 05 / 06Command and arithmetic substitutionCapture a command's output with $(...), do integer math with $((...)), and avoid the pitfalls: stripped newlines, padded wc output, no floats, leading zeros.8 min
  6. 06 / 06Word splitting and the order of expansionThe fixed sequence Bash follows before running a command, why unquoted variables split and glob, and how IFS, set -x and quote removal fit in.22 min

Scripting basics

6 lessons

  1. 01 / 06Your first script - shebang and execute bitTurn commands into a reusable script file: the #! line that names the interpreter, the execute permission, and why a script needs ./ to run.12 min
  2. 02 / 06Exit status and && / || listsEvery command ends with a number, 0 for success. Read it with $?, chain commands on it with && and ||, and avoid the A && B || C trap.15 min
  3. 03 / 06Conditionals with if, test and double bracketsHow if decides using an exit status, what [ ] and [[ ]] really are, the common file and string tests, and the string-versus-number traps.8 min
  4. 04 / 06Loops - for, while and untilRepeat work over files, lists, counters and lines of input with for, while and until, and avoid the classic traps of looping over ls output.10 min
  5. 05 / 06Case statementsMatch one value against several glob patterns with case, handle several spellings with |, set a default with *), and know which terminators need Bash 4.16 min
  6. 06 / 06Functions, arguments and scopeName a block of commands with a function, pass it arguments with $1 and $@, return a status or output, and keep variables inside with local.10 min

Scripting in depth

7 lessons

  1. 01 / 07Parsing options with getoptsGive a script real command-line options with getopts: flags, options with values, error handling, OPTIND and shift, and where getopts stops.5 min
  2. 02 / 07Reading input and here documentsRead user input and file lines with read -r, split fields with IFS, and feed blocks of text to commands with here documents and here strings.7 min
  3. 03 / 07Arrays and associative arraysHold lists safely in indexed arrays, count by key with associative arrays, and see why macOS's Bash 3.2 lacks associative arrays and mapfile.7 min
  4. 04 / 07Strict mode - set -e, -u and pipefailWhat set -e, set -u and set -o pipefail each change, the cases where -e silently does nothing, and why strict mode is a safety net, not a guarantee.10 min
  5. 05 / 07Traps and cleanupRun cleanup code however a script ends with trap on EXIT and signals, create temp files safely with mktemp, and know what a trap cannot catch.15 min
  6. 06 / 07Subshells and process substitutionKnow when Bash quietly runs code in a copy of itself, why variables set there vanish, and how <(command) feeds a command's output to tools that want files.8 min
  7. 07 / 07Debugging with set -x and ShellCheckFind shell script bugs by tracing execution with set -x and a custom PS4, checking syntax with bash -n, and linting with ShellCheck before you run.15 min

Processes and jobs

5 lessons

  1. 01 / 05Processes: ps, top and the process treeSee what is running with ps and top, read PID, PPID and STAT columns, walk a process's parents up to PID 1, and spot zombies. macOS flags noted.20 min
  2. 02 / 05Signals and killSignals are how you ask a process to stop, reload or pause. Learn kill, SIGTERM versus SIGKILL, the 128+n exit codes, and pkill. Numbers differ on macOS.5 min
  3. 03 / 05Job control: foreground and backgroundRun a command in the background with &, suspend with Ctrl-Z, resume with bg and fg, and manage jobs by %number using jobs, kill and wait.11 min
  4. 04 / 05Surviving logout: nohup, disown and tmuxWhy closing a terminal kills your background jobs (SIGHUP) and three fixes: nohup before starting, disown after, and tmux to detach a whole session.9 min
  5. 05 / 05Running things later: cron and atSchedule commands with crontab's five fields and run one-off jobs with at. Why a cron job fails when the same command works at your prompt.19 min

Working interactively

5 lessons

  1. 01 / 05History and readline shortcutsSearch and reuse past commands with Ctrl-R, !! and !$, edit the line with readline keys, and tune HISTCONTROL so your history stays useful. Tested in Bash 5.3.7 min
  2. 02 / 05Aliases and shell functions in rc filesShorten repeated commands with aliases, use functions when you need arguments, and put both in an rc file. Includes where aliases silently do not work.10 min
  3. 03 / 05Customizing the promptBuild a Bash prompt from PS1 escapes, add colour without breaking line wrapping, show the git branch with a function, and use PROMPT_COMMAND.20 min
  4. 04 / 05Tab completionHow Bash completes commands, paths and variables on Tab, why flags and subcommands only complete with extra scripts, and how to write your own with complete.3 min
  5. 05 / 05Dotfiles and configuration managementKeep your shell config in a Git repo and install it on any machine: a symlink script, the bare-repo method, and what GNU Stow adds. Mind the secrets.12 min

Everyday tools

6 lessons

  1. 01 / 06Archives with tar and gzipBundle a directory with tar, compress with gzip, list before extracting, and avoid the traps: leading slashes, -C, and macOS zcat. Tested with bsdtar.8 min
  2. 02 / 06Disk usage with df and duFind out how full a disk is with df and what filled it with du. Covers -h, -s, depth limits, sorting, and the BSD flags that differ on macOS.20 min
  3. 03 / 06diff and patchCompare files and directories with diff, read unified diffs, share a change as a patch file, apply it with patch -p1, undo it with -R, and handle rejects.10 min
  4. 04 / 06Fetching with curl and wgetFetch URLs from the shell with curl: quiet mode, saving files, headers, status codes, -f for scripts, redirects. Why a 404 still exits 0. wget compared.14 min
  5. 05 / 06JSON on the command line with jqRead, filter and reshape JSON in a pipeline with jq: paths, select, map, -r, @csv, --arg, group_by, and the exit codes that tell you a filter found nothing.17 min
  6. 06 / 06Remote work with ssh, scp and rsyncRun commands on another machine with ssh, copy files with scp, and sync directories with rsync. Trailing slashes, dry runs, --delete, and what I could not test.11 min

Writing scripts that last

5 lessons

  1. 01 / 05Portability: POSIX sh and BashDecide whether a script targets POSIX sh or Bash, find bashisms with ShellCheck, and see what /bin/sh, dash and the macOS Bash 3.2 each accept. Tested on macOS.13 min
  2. 02 / 05Structure and style: main functions and shfmtLay out a script with functions and a main, guard it so it can be sourced for tests, and let shfmt and ShellCheck settle formatting. Run on shfmt 3.14.3 min
  3. 03 / 05Safe temporary files and atomic writesCreate temp files with mktemp instead of guessable names, clean up with a trap, and replace files atomically with write-then-mv. BSD mktemp differences noted.7 min
  4. 04 / 05Logging, usage messages and exit codesMake a script behave like a real command: usage text, messages on stderr, a small log function, and exit codes that mean something. Run on Bash 5.3.7 min
  5. 05 / 05Testing scripts with BatsWrite automated tests for shell scripts with Bats: @test blocks, run, status and output, temp dirs, skip, and sourcing functions. Run on bats-core 1.14.23 min
Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark