120 cards
Bash, the Bourne Again SHell, is a Unix shell and command language written as a free software replacement for the original Bourne shell. It serves as the default login shell on most Linux distributions and, before macOS Catalina, on Apple's desktop operating systems as well. Because Bash is installed almost everywhere...
A Bash variable is a named storage location for a value. Variables are assigned with NAME=value — critically, with no spaces around the = sign, because Bash treats VAR = value as a command named VAR with two arguments = and value. Values are referenced as \(NAME or, more explicitly and safely, as \){NAME}. The braced f...
Conditional execution in Bash revolves around if, elif, else, and fi. The condition itself is a list of commands whose exit status determines the branch: zero is true and non-zero is false. The three most common test constructs are [ ], [[ ]], and (( )). The single-bracket [ ... ] is the POSIX test builtin: it is porta...
Bash offers several ways to iterate. The most basic form is for name in list; do body; done, where the list may be a literal set of words, a glob, the output of a command substitution, or an array expansion. Because unquoted globs and command substitutions are subject to word splitting, list iteration over arrays shoul...
Functions are defined in Bash with name() { commands; } or with the keyword form function name { commands; }. The body of a function executes in the same shell environment as the caller — there is no automatic local scope — so variables assigned inside a function leak into the surrounding scope unless they are declared...
Bash supports both indexed arrays and associative arrays (dictionaries). Indexed arrays are declared with arr=(one two three) or by element with arr[0]=one, and individual elements are accessed with \({arr[0]}. All elements are accessed with \){arr[@]} (each as a separate word) or \({arr[*]} (joined into one word), and...
The read builtin is the primary way to ingest input. read -rp "Prompt: " answer reads a single line with a prompt and without backslash interpretation, while while IFS= read -r line; do ...; done < file.txt is the canonical pattern for iterating over a file. The variant read -d DELIM changes the line terminator, whi...
A subshell, written ( commands ) or produced by backgrounding, runs its commands in a child of the current shell. Any changes to variables, the working directory, or shell options do not affect the parent once the subshell exits, which makes subshells ideal for isolating a temporary cd — as in (cd /tmp && cmd)...