Shell & Bash
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.
What 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.Anatomy 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.Getting 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.Moving 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.The 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.Startup 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.Listing 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.Creating, 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.Permissions 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.Hard 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.Globbing and wildcardsThe shell, not the command, expands *, ? and [...] into file names. See hidden files, unmatched patterns and quoting, plus globstar, nullglob and extglob.Finding 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.stdin, 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.RedirectionPoint 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.Pipes 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.Viewing 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.Searching with grepFilter lines with grep: count, invert, ignore case, print only matches, search trees, and read exit statuses. macOS BSD grep has no -P.sort, 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.Editing 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.Processing 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.Quoting - 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.Variables and the environmentShell variables versus environment variables, how export hands a value to child processes, and the one-shot VAR=value command form.Parameter expansionUse ${var} forms to supply defaults, trim prefixes and suffixes, replace text, change case and measure length without calling sed, cut or basename.Brace 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.Command 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.Word 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.Your 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.Exit 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.Conditionals 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.Loops - 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.Case statementsMatch one value against several glob patterns with case, handle several spellings with |, set a default with *), and know which terminators need Bash 4.Functions, 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.Parsing options with getoptsGive a script real command-line options with getopts: flags, options with values, error handling, OPTIND and shift, and where getopts stops.Reading 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.Arrays 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.Strict 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.Traps 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.Subshells 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.Debugging 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.Processes: 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.Signals 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.Job 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.Surviving 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.Running 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.History 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.Aliases 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.Customizing 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.Tab 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.Dotfiles 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.Archives 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.Disk 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.diff 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.Fetching 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.JSON 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.Remote 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.Portability: 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.Structure 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.Safe 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.Logging, 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.Testing 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.
What the shell is
- What 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.
- Anatomy 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.
- Getting 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.
- Moving 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.
- The 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.
- Startup 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.
Files and directories
- Listing 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.
- Creating, 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.
- Permissions 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.
- Hard 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.
- Globbing and wildcardsThe shell, not the command, expands *, ? and [...] into file names. See hidden files, unmatched patterns and quoting, plus globstar, nullglob and extglob.
- Finding 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.
Streams, pipes and text
- stdin, 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.
- RedirectionPoint 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.
- Pipes 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.
- Viewing 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.
- Searching with grepFilter lines with grep: count, invert, ignore case, print only matches, search trees, and read exit statuses. macOS BSD grep has no -P.
- sort, 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.
- Editing 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.
- Processing 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.
Quoting and expansion
- Quoting - 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.
- Variables and the environmentShell variables versus environment variables, how export hands a value to child processes, and the one-shot VAR=value command form.
- Parameter expansionUse ${var} forms to supply defaults, trim prefixes and suffixes, replace text, change case and measure length without calling sed, cut or basename.
- Brace 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.
- Command 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.
- Word 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.
Scripting basics
- Your 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.
- Exit 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.
- Conditionals 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.
- Loops - 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.
- Case statementsMatch one value against several glob patterns with case, handle several spellings with |, set a default with *), and know which terminators need Bash 4.
- Functions, 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.
Scripting in depth
- Parsing options with getoptsGive a script real command-line options with getopts: flags, options with values, error handling, OPTIND and shift, and where getopts stops.
- Reading 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.
- Arrays 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.
- Strict 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.
- Traps 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.
- Subshells 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.
- Debugging 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.
Processes and jobs
- Processes: 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.
- Signals 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.
- Job 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.
- Surviving 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.
- Running 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.
Working interactively
- History 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.
- Aliases 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.
- Customizing 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.
- Tab 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.
- Dotfiles 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.
Everyday tools
- Archives 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.
- Disk 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.
- diff 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.
- Fetching 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.
- JSON 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.
- Remote 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.
Writing scripts that last
- Portability: 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.
- Structure 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.
- Safe 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.
- Logging, 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.
- Testing 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.