🐚 Bash

← Back to Cheatsheets

A quick-reference cheatsheet for Bash scripting and the command line. Bash is both an interactive shell and a scripting language available on virtually every Unix-like system. Scripts start with #!/usr/bin/env bash and should be made executable with chmod +x script.sh.

Resources

GNU Bash manual BashGuide — wooledge wiki ShellCheck — linter explainshell.com devhints.io/bash — cheatsheet

Variables

Variables are untyped strings by default. No spaces around = when assigning. Always double-quote variable expansions ("$var") to prevent word splitting and glob expansion on values that contain spaces or special characters.

Strings & Substitution

Bash provides built-in string manipulation via parameter expansion — no need to invoke external tools like sed or awk for simple operations. Command substitution captures the output of a command into a variable.

Control Flow

Bash conditions test exit codes — 0 means true, non-zero means false. Use [[ ... ]] (Bash built-in) instead of [ ... ] (POSIX test) — it handles empty strings and spaces safely without quoting tricks, and supports &&, ||, and regex matching.

Functions

Functions in Bash are just named command groups. Arguments are accessed as $1, $2, etc. — there is no parameter list. Use local to scope variables to the function; without it, all variables are global by default.

Arrays

Bash supports indexed and associative arrays. Always quote array expansions with "${arr[@]}" to preserve elements that contain spaces. "${arr[*]}" joins all elements into one string.

I/O & Redirection

Every process has three standard file descriptors: stdin (0), stdout (1), and stderr (2). Redirection operators route these streams to files or other commands. Pipes chain commands so stdout of one becomes stdin of the next.

Processes & Jobs

Bash can run commands in the background, wait for them, and check their exit codes. The trap built-in lets you handle signals and run cleanup code when a script exits.

Common Patterns

A few idioms that make scripts more robust and maintainable. set -euo pipefail should be at the top of almost every script — it prevents silent failures that are hard to debug later.