Bash 5 reference · 21 entries

Bash Shell Builtins and Syntax

Bash builtins and syntax: printf, read, conditions, loops, functions, arrays, expansions, redirection, strict mode and traps.

NameDescriptionSince
printf Print formatted text with format specifiers like %s, %d and %.2f; more portable and predictable than echo.
read Read a line from standard input into variables, splitting on IFS; use -r to keep backslashes and -p for a prompt.
mapfile Read all lines of input into an indexed array at once (also called readarray), optionally trimming newlines with -t.
[[ ]] Bash's conditional expression: compare strings and numbers, test files, and match glob patterns or regular expressions.
if Run commands depending on whether a command succeeds (exit status 0), with optional elif and else branches.
case Match a value against glob patterns and run the first matching branch; cleaner than long if/elif chains.
for Loop over words, files, ranges or array elements, or use the C-style form for counters.
while Repeat commands while a condition succeeds; with read, it's the standard way to process input line by line.
function Group commands into a named function that takes arguments like a script ($1, $@) and returns an exit status.
local Declare variables that exist only inside the current function, so they don't overwrite globals with the same name.
declare Declare variables with attributes: arrays, associative arrays, integers, read-only values and exported variables.
arrays Indexed and associative arrays: create, append, read elements, count, slice and loop over them safely.
${...} expansion Defaults, length, substrings, prefix and suffix removal, search and replace, and case conversion on variables.
$(( )) arithmetic Evaluate integer arithmetic and comparisons with $(( )) and (( )); Bash has no floating point, so use awk or bc.
redirection Send output to files, read input from files, merge stderr into stdout, and discard output with /dev/null.
here-document Feed multiple lines to a command with <<EOF; quote the marker to stop variable expansion, use <<- to strip tabs.
set -euo pipefail Turn on strict mode: exit on errors (-e), fail on unset variables (-u), and fail pipelines when any part fails.
trap Run commands when the script exits or receives a signal; the standard way to clean up temporary files and child processes.
export Mark variables so child processes inherit them; one-off variables can also be set for a single command.
source Run a file's commands in the current shell, so its variables and functions stay defined; . is the POSIX spelling.
getopts Parse short command-line options such as -v and -o FILE in scripts, with errors for unknown options.

Was this page helpful?