# Code Reference (/docs) Welcome to the **Code Reference** docs — focused notes for everyday coding. Each page covers overview, core concepts, examples, pitfalls, and related links. ## Topics [#topics] ## How notes are structured [#how-notes-are-structured] 1. **Overview** — what and when 2. **Core concepts** — APIs / syntax 3. **Examples** — runnable snippets 4. **Pitfalls** — mistakes to avoid 5. **Related** — sibling notes Built with [Fumadocs](https://www.fumadocs.dev/docs). # Arrays (/docs/bash/arrays) # Arrays [#arrays] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Bash has indexed arrays (`declare -a`) and associative arrays (`declare -A`, bash 4+). Always expand with `"$\{arr[@]\}"` to preserve elements. Arrays are the safe alternative to storing lists in a single string. ## 🔧 Core concepts [#-core-concepts] | Syntax | Meaning | | ---------------- | -------------------------------------- | | `arr=(a b c)` | Indexed array | | `arr[i]=val` | Set element | | `"$\{arr[@]\}"` | All elements (separate words) | | `"$\{arr[*]\}"` | Joined with first IFS char when quoted | | `$\{#arr[@]\}` | Length | | `$\{!arr[@]\}` | Indices / keys | | `arr+=(x)` | Append | | `unset 'arr[i]'` | Remove element | | `declare -A map` | Associative array | | `map=([k]=v)` | Assoc init | Sparse indexed arrays keep original indices after `unset`. Iterate keys with `"$\{!arr[@]\}"`. ## 💡 Examples [#-examples] **Indexed:** ```shellscript files=("a b.txt" "c.txt") files+=("d.txt") echo "${#files[@]}" for f in "${files[@]}"; do echo "$f" done echo "${files[0]}" ``` **Slice and copy:** ```shellscript slice=("${files[@]:1:2}") # 2 elems from index 1 copy=("${files[@]}") ``` **Associative:** ```shellscript declare -A ports=([web]=80 [db]=5432) ports[cache]=6379 for k in "${!ports[@]}"; do echo "$k -> ${ports[$k]}" done ``` **From command (mapfile):** ```shellscript mapfile -t lines < file.txt mapfile -d '' -t paths < <(find . -print0) ``` ## ⚠️ Pitfalls [#️-pitfalls] * `"$\{arr[@]\}"` vs `$\{arr[@]\}`: always quote. * `"$\{arr[*]\}"` is one string when quoted—wrong for iterating items with spaces. * Associative arrays need bash 4+; macOS system bash may be 3.2—use Homebrew bash or avoid. * `arr=($string)` splits on IFS; prefer `read -a` or `mapfile`. * `unset arr` removes whole array; `unset 'arr[0]'` one element. * Indices are not re-packed after delete; don’t assume contiguous `0..n-1`. ## 🔗 Related [#-related] * [variables.md](/docs/bash/variables) * [quoting.md](/docs/bash/quoting) * [loops.md](/docs/bash/loops) * [string\_ops.md](/docs/bash/string-ops) * [globbing.md](/docs/bash/globbing) # Conditionals (/docs/bash/conditionals) # Conditionals [#conditionals] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Bash branches with `if`/`elif`/`else`, `case`, and `[[ ]]` / `[ ]` / `(( ))` tests. Prefer `[[ ]]` for strings and files; `(( ))` for integers. Exit status `0` is true; non-zero is false. ## 🔧 Core concepts [#-core-concepts] | Construct | Use | | -------------------- | -------------------------------------- | | `if cmd; then …; fi` | Branch on exit status | | `[[ expr ]]` | Bash test (safer, richer) | | `[ expr ]` / `test` | POSIX test | | `(( expr ))` | Arithmetic; 0 → false, non-zero → true | | `case $x in … esac` | Pattern match | | `&&` / `\|\|` | Short-circuit | **`[[ ]]` operators:** `-eq -ne -lt -le -gt -ge` (numbers as strings carefully), `=`, `==`, `!=`, `=~` regex, `-z` empty, `-n` non-empty, `-f -d -e -L -r -w -x` files, `-nt` / `-ot` newer/older. ## 💡 Examples [#-examples] **File and string checks:** ```shellscript if [[ -f "$config" && -r "$config" ]]; then source "$config" elif [[ -z "${config:-}" ]]; then echo "No config" >&2 exit 1 fi ``` **Numeric:** ```shellscript if (( count > 10 )); then echo "too many" fi if [[ "$count" -gt 10 ]]; then …; fi # integer compare in [[ ]] ``` **Regex and case:** ```shellscript if [[ "$email" =~ ^[A-Za-z0-9._%+-]+@ ]]; then echo "looks like email" fi case "$1" in start|on) start_svc ;; stop|off) stop_svc ;; *) echo "usage: $0 start|stop" >&2; exit 2 ;; esac ``` **One-liners:** ```shellscript [[ -d "$dir" ]] || mkdir -p "$dir" command -v jq >/dev/null || { echo "jq required"; exit 1; } ``` ## ⚠️ Pitfalls [#️-pitfalls] * `[ $a = $b ]` breaks on empty/spaces; always quote: `[ "$a" = "$b" ]`. * `==` inside `[ ]` is non-POSIX; use `=` or switch to `[[ ]]`. * `(( ))` treats empty/unset as 0 with `set -u` risks—initialize first. * `=~` right-hand side should be unquoted to be a regex; quoted = literal. * Prefer `[[ ]]` over `[ ]` in bash scripts; keep `[ ]` for `sh` portability. * `if cmd` tests exit code—not stdout. Capture output separately. ## 🔗 Related [#-related] * [exit\_codes.md](/docs/bash/exit-codes) * [loops.md](/docs/bash/loops) * [quoting.md](/docs/bash/quoting) * [variables.md](/docs/bash/variables) * [debugging.md](/docs/bash/debugging) # Cron (/docs/bash/cron) # Cron [#cron] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Cron schedules recurring jobs via crontab entries. Each line is five time fields plus a command. Cron runs with a minimal environment—always set `PATH`, use absolute paths, and redirect logs. Prefer systemd timers on modern Linux when available. ## 🔧 Core concepts [#-core-concepts] | Field | Values | | ------ | --------------- | | Minute | 0–59 | | Hour | 0–23 | | Dom | 1–31 | | Month | 1–12 | | Dow | 0–7 (0/7 = Sun) | | `*` | Any | | `*/n` | Every n | | `a,b` | List | | `a-b` | Range | | Command | Role | | -------------- | -------------------- | | `crontab -e` | Edit user crontab | | `crontab -l` | List | | `crontab -r` | Remove (dangerous) | | `/etc/cron.d/` | System drop-in files | Special strings (Vixie): `@reboot`, `@daily`, `@hourly`, `@weekly`, `@monthly`. ## 💡 Examples [#-examples] **User crontab entries:** ```cron SHELL=/bin/bash PATH=/usr/local/bin:/usr/bin:/bin MAILTO="" # Every day at 02:30 30 2 * * * /home/ada/bin/backup.sh >>/home/ada/logs/backup.log 2>&1 # Every 15 minutes */15 * * * * /usr/bin/curl -fsS https://example.com/health >/dev/null @reboot /home/ada/bin/on-boot.sh ``` **Wrapper script:** ```shellscript #!/usr/bin/env bash set -euo pipefail cd "$HOME/app" /usr/bin/flock -n /tmp/app-cron.lock ./job.sh ``` **Systemd alternative (sketch):** ```ini # app.timer + app.service with OnCalendar=*-*-* 02:30:00 ``` ## ⚠️ Pitfalls [#️-pitfalls] * Cron’s `PATH` is short—commands that work interactively may “not be found”. * `%` in commands is special in crontab (newline)—escape as `\%`. * No TTY; don’t assume interactive prompts or ssh-agent unless configured. * Overlapping runs: use `flock` to prevent pile-ups. * Timezone is the system timezone unless you set `TZ=`. * `crontab -r` deletes without confirmation on some systems. ## 🔗 Related [#-related] * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [shebang.md](/docs/bash/shebang) * [exit\_codes.md](/docs/bash/exit-codes) * [debugging.md](/docs/bash/debugging) * [ssh.md](/docs/bash/ssh) # Debugging (/docs/bash/debugging) # Debugging [#debugging] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Debug bash with tracing (`set -x`), verbose mode, ShellCheck, and strategic logging. Reproduce with the same options and environment as production. Prefer small reproducible snippets over editing large scripts blindly. ## 🔧 Core concepts [#-core-concepts] | Tool | Purpose | | ------------------- | ------------------------------ | | `set -x` / `set +x` | Trace expanded commands | | `set -v` | Print input lines as read | | `PS4` | Prefix for `set -x` traces | | `bash -n script` | Syntax check only | | `bash -x script` | Run with trace | | `trap` | Catch `ERR` / `DEBUG` / `EXIT` | | ShellCheck | Lint common bugs | | `printf '%q\n'` | Show shell-escaped values | `ERR` trap runs when a command fails (with `set -e` nuances). `DEBUG` trap runs before each command. ## 💡 Examples [#-examples] **Trace with context:** ```shellscript export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: ' set -x # … suspect code … set +x ``` **ERR trap:** ```shellscript trap 'echo "ERR at ${BASH_SOURCE}:${LINENO}: $BASH_COMMAND" >&2' ERR set -euo pipefail ``` **Inspect values:** ```shellscript declare -p var printf 'args:'; printf ' <%q>' "$@"; echo type -a cmd command -v cmd ``` **Dry syntax + lint:** ```shellscript bash -n ./deploy.sh shellcheck -x ./deploy.sh ``` **Conditional debug flag:** ```shellscript debug() { [[ "${DEBUG:-}" == 1 ]] && printf '%s\n' "$*" >&2; } debug "port=$port" ``` ## ⚠️ Pitfalls [#️-pitfalls] * `set -x` prints secrets—disable around credential handling or redact. * Tracing changes timing (Heisenbugs in races). * `bash -n` does not catch runtime logic errors. * Don’t leave `set -x` on in production cron output floods. * Pipeline failures need `pipefail` to surface in traces meaningfully. * Subshells complicate stack traces—note `(…)` boundaries. ## 🔗 Related [#-related] * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [exit\_codes.md](/docs/bash/exit-codes) * [shebang.md](/docs/bash/shebang) * [variables.md](/docs/bash/variables) * [pipes\_redirection.md](/docs/bash/pipes-redirection) # Environment Basics (/docs/bash/environment-basics) # Environment Basics [#environment-basics] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] The **environment** is a set of key/value variables available to your shell and the programs it starts. Common ones: `PATH`, `HOME`, `USER`, `PWD`. Scripts often read `VAR=value` settings for configuration. ## 🔧 Core concepts [#-core-concepts] | Idea | Meaning | | --------------------- | ---------------------------------------------------------- | | Environment variable | Name → string value | | `export` | Mark a variable for child processes | | `PATH` | Colon-separated list of directories to search for commands | | `$VAR` / `"$\{VAR\}"` | Expand a variable | | `.env` files | Convention for app config (not automatic in Bash) | Shell variables and environment variables are related; `export` promotes a shell variable into the environment. ## 💡 Examples [#-examples] **Inspect common variables:** ```shellscript echo "$HOME" echo "$USER" echo "$PWD" echo "$PATH" ``` **Set for one command:** ```shellscript LANG=C date MESSAGE="hi" bash -c 'echo "$MESSAGE"' ``` **Export for the current session:** ```shellscript export APP_ENV=development echo "$APP_ENV" env | grep APP_ENV ``` **Add a directory to PATH (session only):** ```shellscript export PATH="$HOME/bin:$PATH" which python || true ``` ## ⚠️ Pitfalls [#️-pitfalls] * Always quote expansions: `"$VAR"` — unquoted values with spaces break. * `export FOO = bar` is wrong (spaces around `=`). * Changing `PATH` incorrectly can make every command “not found.” * Putting secrets in world-readable scripts or committing `.env` is unsafe. ## 🔗 Related [#-related] * [getting\_started.md](/docs/bash/getting-started) * [navigation.md](/docs/bash/navigation) * [variables.md](/docs/bash/variables) * [permissions\_basics.md](/docs/bash/permissions-basics) # Exit Codes (/docs/bash/exit-codes) # Exit Codes [#exit-codes] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Every command returns an 8-bit exit status: `0` success, `1–255` failure. Scripts should exit with meaningful codes. `$?` holds the last foreground status; with `pipefail`, pipelines report the rightmost non-zero (or zero if all succeed). ## 🔧 Core concepts [#-core-concepts] | Code | Convention | | ------- | --------------------------------------------- | | `0` | Success | | `1` | General error | | `2` | Misuse of shell builtins / bad usage (common) | | `126` | Found but not executable | | `127` | Command not found | | `128+N` | Fatal signal N (e.g. 130 = SIGINT) | | `255` | Out-of-range `exit` (wrapped) | | Tool | Role | | ----------------- | ------------------------------ | | `exit N` | End shell/script with status N | | `return N` | End function with status N | | `$?` | Last status | | `set -e` | Exit on failure (with caveats) | | `set -o pipefail` | Pipeline status | sysexits.h codes (`EX_USAGE=64`, etc.) appear in some tools but are optional for scripts. ## 💡 Examples [#-examples] **Check and propagate:** ```shellscript if ! git pull; then echo "pull failed: $?" >&2 exit 1 fi ``` **Meaningful script exits:** ```shellscript usage() { echo "usage: $0 " >&2; exit 2; } [[ $# -eq 1 ]] || usage [[ -f "$1" ]] || { echo "missing file" >&2; exit 1; } ``` **Capture without losing status:** ```shellscript output="$(cmd)" || status=$? status=${status:-0} ``` **Pipeline:** ```shellscript set -o pipefail false | true # status 1 with pipefail; 0 without ``` ## ⚠️ Pitfalls [#️-pitfalls] * `exit` with values outside 0–255 are truncated modulo 256. * `cmd || true` swallows failures—use only when intentional. * `set -e` is disabled in some contexts (`if`, `&&`, `||`, `!`)—know the rules. * Assignments: `local x=$(false)` may not trigger `set -e` as expected. * Background jobs: `wait $pid` yields that job’s status. * Don’t parse `$?` after another command overwrote it—save immediately. ## 🔗 Related [#-related] * [conditionals.md](/docs/bash/conditionals) * [pipes\_redirection.md](/docs/bash/pipes-redirection) * [debugging.md](/docs/bash/debugging) * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [functions.md](/docs/bash/functions) # Functions (/docs/bash/functions) # Functions [#functions] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Functions group reusable commands. They share the shell’s process (unless you spawn a subshell). Arguments arrive as `$1`…`"$@"`. Prefer `local` for internals and explicit `return` status (0–255). ## 🔧 Core concepts [#-core-concepts] | Topic | Detail | | ------------ | --------------------------------------------- | | Define | `name() \{ …; \}` or `function name \{ …; \}` | | Call | `name arg1 arg2` (no parentheses) | | Args | `$1`, `$2`, `"$@"`, `$#` | | Locals | `local var=value` | | Return | `return N` (exit status); stdout for data | | Scope | Dynamic; locals shadow globals | | `declare -f` | List function bodies | Functions cannot return structured data via `return`—print to stdout and capture with `$(...)`, or use namerefs (`declare -n`) / globals carefully. ## 💡 Examples [#-examples] **Basic with locals:** ```shellscript greet() { local who="${1:-world}" echo "Hello, $who" } greet "Ada" ``` **Return status vs output:** ```shellscript is_dir() { [[ -d "$1" ]] } path_join() { local a="$1" b="$2" echo "${a%/}/$b" } if is_dir "/tmp"; then out="$(path_join "/var" "log")" fi ``` **Nameref (bash 4.3+):** ```shellscript append() { local -n _arr=$1 shift _arr+=("$@") } list=() append list a b ``` **Guard usage:** ```shellscript usage() { echo "usage: $0 " >&2; } main() { [[ $# -ge 1 ]] || { usage; return 2; } … } main "$@" ``` ## ⚠️ Pitfalls [#️-pitfalls] * `local var=$(cmd)` masks `cmd`’s exit status; split assign and check. * Forgetting `local` leaks variables into the global scope. * `return` outside a function exits the shell when sourced carefully—use only in functions. * Recursion depth and performance: bash functions are not optimized like compiled code. * Defining functions in a pipeline/subshell does not affect the parent shell. * Name clashes with external commands: prefer project prefixes (`myapp_`). ## 🔗 Related [#-related] * [variables.md](/docs/bash/variables) * [exit\_codes.md](/docs/bash/exit-codes) * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [subshells.md](/docs/bash/subshells) * [getopts.md](/docs/bash/getopts) # getopts (/docs/bash/getopts) # getopts [#getopts] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] `getopts` parses single-letter command-line options in a portable way. It handles clustered flags (`-abc`), optional/required arguments, and error reporting. For long options (`--verbose`), use a manual loop or external tools—not plain `getopts`. ## 🔧 Core concepts [#-core-concepts] | Piece | Role | | ------------------------ | -------------------------------------------------- | | `getopts optstring name` | Parse next option into `name` | | `optstring` | Letters; append `:` if option requires an argument | | Leading `:` in optstring | Silent error mode (`?` / `:` in name) | | `$OPTARG` | Argument value or bad option letter | | `$OPTIND` | Next argv index to process | | `--` | End of options (caller convention) | After the loop, remaining operands are `"$@"` shifted with `shift $((OPTIND - 1))`. ## 💡 Examples [#-examples] **Classic flags:** ```shellscript #!/usr/bin/env bash verbose=0 file="" while getopts ':vf:' opt; do case "$opt" in v) verbose=1 ;; f) file="$OPTARG" ;; :) echo "option -$OPTARG requires an argument" >&2; exit 2 ;; ?) echo "unknown option -$OPTARG" >&2; exit 2 ;; esac done shift $((OPTIND - 1)) echo "verbose=$verbose file=$file args: $*" ``` **Usage pattern:** ```shellscript usage() { cat <<'EOF' >&2 usage: tool [-v] [-f file] [args...] EOF exit 2 } ``` **Reset for reuse (functions):** ```shellscript OPTIND=1 ``` ## ⚠️ Pitfalls [#️-pitfalls] * `getopts` does not parse `--long` options. * Missing required args: with silent mode, `opt` is `:` and `OPTARG` is the option letter. * Forgetting `shift $((OPTIND - 1))` leaves flags in `"$@"`. * `OPTIND` is global—reset when calling `getopts` multiple times. * Option arguments starting with `-` are still accepted as `OPTARG`. * Prefer `getopts` over hand-rolled `$#` loops for short options. ## 🔗 Related [#-related] * [functions.md](/docs/bash/functions) * [variables.md](/docs/bash/variables) * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [conditionals.md](/docs/bash/conditionals) * [exit\_codes.md](/docs/bash/exit-codes) # Getting Started with Bash (/docs/bash/getting-started) # Getting Started with Bash [#getting-started-with-bash] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Bash (Bourne Again SHell) is a command-line shell and scripting language common on Linux and macOS. You type commands interactively or save them in a script (`*.sh`) starting with a shebang. ## 🔧 Core concepts [#-core-concepts] | Idea | Meaning | | ----------- | ------------------------------------------------- | | Shell | Program that reads commands and runs programs | | Prompt | Where you type (`$` often means a normal user) | | Command | Program name + arguments: `ls -la` | | Script | File of commands executed in order | | Shebang | `#!/usr/bin/env bash` on line 1 of scripts | | Exit status | `0` usually means success; non-zero means failure | On Windows you can use Git Bash, WSL, or another Unix-like environment. ## 💡 Examples [#-examples] **Who am I / where am I:** ```shellscript whoami pwd echo "Hello from Bash" ``` **Check Bash version:** ```shellscript bash --version echo "$BASH_VERSION" ``` **Minimal script (`hello.sh`):** ```shellscript #!/usr/bin/env bash set -euo pipefail echo "Hello, World!" ``` ```shellscript chmod +x hello.sh ./hello.sh ``` **Run a one-liner without a file:** ```shellscript bash -c 'echo hi; pwd' ``` ## ⚠️ Pitfalls [#️-pitfalls] * Spaces matter: `cd My Dir` fails; use `cd "My Dir"`. * Your login shell might be zsh on macOS — scripts can still use Bash via shebang. * Copying Windows paths (`C:\...`) into Bash needs `/c/...` or WSL paths. * Forgetting `chmod +x` leads to “Permission denied” on `./script.sh`. ## 🔗 Related [#-related] * [hello\_world.md](/docs/bash/hello-world) * [navigation.md](/docs/bash/navigation) * [permissions\_basics.md](/docs/bash/permissions-basics) * [environment\_basics.md](/docs/bash/environment-basics) # Globbing (/docs/bash/globbing) # Globbing [#globbing] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Globs (pathname expansion) match filenames with `*`, `?`, and `[]` before the command runs. Unlike regex, `*` never matches `/` across directories unless globstar is on. Quote patterns when you want literals; enable `nullglob` / `failglob` for safer scripts. ## 🔧 Core concepts [#-core-concepts] | Pattern | Matches | | ----------------- | ------------------------------------- | | `*` | Any string except `/` | | `?` | Single character | | `[abc]` / `[a-z]` | Character class | | `[!a]` / `[^a]` | Negated class | | `**` | Recursive (needs `shopt -s globstar`) | | `*(pat)` etc. | Extglob patterns (`shopt -s extglob`) | | `shopt` | Effect | | ------------ | ---------------------- | | `nullglob` | Unmatched glob → empty | | `failglob` | Unmatched glob → error | | `dotglob` | Include `.hidden` | | `nocaseglob` | Case-insensitive | | `globstar` | Enable `**` | ## 💡 Examples [#-examples] **Safe iteration:** ```shellscript shopt -s nullglob for f in *.log; do echo "$f" done ``` **Extglob:** ```shellscript shopt -s extglob rm -- !(keep|also-keep).tmp ls *.(jpg|png|gif) ``` **Globstar:** ```shellscript shopt -s globstar nullglob for f in **/*.py; do echo "$f" done ``` **Disable expansion:** ```shellscript echo "*.txt" # literal printf '%s\n' *.txt # expanded list ``` ## ⚠️ Pitfalls [#️-pitfalls] * Default: unmatched `*.txt` stays as the literal string `*.txt`—dangerous in `rm`. * Globs don’t sort the way you always expect across locales; sort explicitly if needed. * `**` without `globstar` is just two `*` tokens in some contexts—enable the option. * Brace expansion `\{a,b\}` is not globbing; it runs even if files don’t exist. * Leading `.` files ignored unless `dotglob` or pattern starts with `.`. * Never parse `ls`; use globs or `find`. ## 🔗 Related [#-related] * [quoting.md](/docs/bash/quoting) * [loops.md](/docs/bash/loops) * [arrays.md](/docs/bash/arrays) * [scripts\_best\_practices.md](/docs/bash/scripts-best-practices) * [string\_ops.md](/docs/bash/string-ops) # Glossary (/docs/bash/glossary) # Glossary [#glossary] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Alphabetical glossary of core Bash terms for shells, scripting, expansion, pipelines, and process control. ## 🔧 Core concepts [#-core-concepts] | Term | Definition | | | -------------------- | ------------------------------------------------------------------------------- | --- | | Alias | A short name that expands to a longer command string. | | | Argument | A token passed to a command after its name. | | | Array | An indexed list of strings accessible as `$\{arr[i]\}`. | | | Brace expansion | Generating multiple strings from patterns like `\{a,b\}` or `\{1..5\}`. | | | Builtin | A command implemented inside the shell, not as an external binary. | | | Command substitution | Capturing a command’s output with `$(...)` or backticks. | | | Conditional | An `if`/`[[ ]]`/`case` construct that branches on tests. | | | Exit code | An integer status (`$?`) where `0` usually means success. | | | Expansion | Transformations Bash applies before running a command (variables, globs, etc.). | | | Function | A named compound command defined in the shell. | | | Glob | A filename pattern using `*`, `?`, or `[]` that expands to matching paths. | | | Here-doc | A multiline string redirected into a command via `<(...)`. | | | Quoting | Rules (`'`, `"`, `\`) that control whether expansion occurs. | | | Redirection | Sending stdin/stdout/stderr to files or other descriptors (`>`, `2>`, `&>`). | | | Shebang | The `#!/bin/bash` line that selects the interpreter for a script. | | | Signal | An OS notification such as `SIGINT` that processes can trap or ignore. | | | Subshell | A child shell environment created by `(...)` or some pipelines. | | | Trap | A handler that runs commands when a signal or exit occurs. | | | Variable | A named string storage slot such as `NAME=value` and `$NAME`. | | | Word splitting | Breaking unquoted expansions on `IFS` characters into multiple fields. | | ## 💡 Examples [#-examples] **Variables, quoting, and exit codes:** ```shellscript name="Ada Lovelace" echo "Hello, $name" grep -q pattern file.txt echo $? ``` **Pipes and redirection:** ```shellscript ps aux | grep nginx | awk '{print $2}' > pids.txt 2>/dev/null ``` **Arrays and globbing:** ```shellscript files=(*.md) echo "${#files[@]} files" printf '%s\n' "${files[@]}" ``` ## ⚠️ Pitfalls [#️-pitfalls] * Confusing **single quotes** (literal) with **double quotes** (allow `$` and `` ` `` expansion). * Mixing **array** indexing with string variables — unquoted `$arr` is not safe iteration. * Treating **exit code** `0` as false in `if` — in Bash, `0` is success/true. * Equating a **subshell** `(cd /tmp; ...)` with changing the parent shell’s directory. * Assuming **glob** failure always errors — unmatched globs may stay literal depending on options. ## 🔗 Related [#-related] * [variables](/docs/bash/variables) * [quoting](/docs/bash/quoting) * [pipes\_redirection](/docs/bash/pipes-redirection) * [arrays](/docs/bash/arrays) * [functions](/docs/bash/functions) * [exit\_codes](/docs/bash/exit-codes) # Hello World (/docs/bash/hello-world) # Hello World [#hello-world] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Bash Hello World prints a line to the terminal with `echo` (or `printf`). It confirms you can run commands and, optionally, execute a script file. ## 🔧 Core concepts [#-core-concepts] | Piece | Role | | -------------- | --------------------------------------- | | `echo` | Print arguments followed by a newline | | `printf` | Formatted print (more predictable) | | Shebang | Selects the interpreter for scripts | | `./file` | Run a file in the current directory | | `bash file.sh` | Run a script without the executable bit | Prefer `printf` when you care about exact formatting; `echo` is fine for learning. ## 💡 Examples [#-examples] **Interactive:** ```shellscript echo "Hello, World!" printf '%s\n' "Hello, World!" ``` **Script file:** ```shellscript #!/usr/bin/env bash echo "Hello, World!" ``` ```shellscript bash hello.sh ``` **With a variable:** ```shellscript #!/usr/bin/env bash name="Ada" echo "Hello, ${name}!" ``` **Show command success:** ```shellscript echo "Hello, World!" echo "exit status was $?" ``` ## ⚠️ Pitfalls [#️-pitfalls] * `echo $name` without quotes breaks on spaces — prefer `"$name"`. * Some `echo` flags differ across systems; `printf` is more portable. * Running `sh hello.sh` may not be Bash if `sh` is dash. * CRLF line endings from Windows editors can break shebang scripts. ## 🔗 Related [#-related] * [getting\_started.md](/docs/bash/getting-started) * [navigation.md](/docs/bash/navigation) * [variables.md](/docs/bash/variables) * [shebang.md](/docs/bash/shebang) # Bash (/docs/bash) # Bash [#bash] Shell scripting essentials. Browse the sidebar for every cheat sheet in this section. ## Sections [#sections] * [Examples](./examples) # Loops (/docs/bash/loops) # Loops [#loops] *Bash · Reference cheat sheet* *** ## 📋 Overview [#-overview] Bash offers `for`, `while`, `until`, and C-style `for (( ))`. Prefer iterating arrays or null-delimited streams over unquoted globs. Use `break` / `continue` to control flow; avoid parsing `ls`. ## 🔧 Core concepts [#-core-concepts] | Loop | Typical use | | --------------------------- | ----------------------- | | `for x in list; do …; done` | Fixed word list / array | | `for ((i=0; i