variables
declare / typeset / readonly
Declares variables with attributes: arrays, associative arrays, integers, readonly, lowercase/uppercase, exported. 'readonly' is a shortcut for 'declare -r' that locks a variable so it cannot be reassigned or unset for the lifetime of the shell.
declare [-aAilrxu] [-p] [NAME[=VALUE] ...] | readonly [-aAf] NAME[=VALUE] ... Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| -a | Indexed array |
| -A | Associative array (bash 4+) |
| -i | Integer — assignments are arithmetic-evaluated |
| -r / readonly | Readonly (cannot be reassigned or unset) |
| -x | Export to environment (like 'export') |
| -p | Print declaration in reusable form |
Examples
declare -A cfg=([host]=localhost [port]=8080) Associative array with two keys (bash 4+).
declare -i n=5; n+=3; echo "$n" Integer attribute — prints 8, not '53'.
readonly VERSION=1.2.3 Constant — any later 'VERSION=...' will fail.
declare -p PATH Prints 'declare -x PATH="..."' showing attributes.
Gotcha
'declare -A' requires bash 4+ — macOS's default /bin/bash 3.2 lacks it. Inside a function, plain 'declare' creates a LOCAL variable, unlike at top level; readonly cannot be undone without exiting the shell.
Related
local
Declares a variable scoped to the current function, hiding any global of the same name during the function's execution. Accepts the same attribute flags as declare (-a, -A, -i, -r, -n, ...).
export
Marks a shell variable (or function with -f) for export to the environment of subsequently executed commands. Without arguments, prints all exported variables in a re-importable format.
unset
Removes a variable or function from the shell — different from setting it to empty. Without a flag it targets variables first, then functions, unless -f or -v is specified.
shift
Renames positional parameters: $2 becomes $1, $3 becomes $2, and so on, decrementing $#. Optional N shifts by N positions and is common in manual argument parsing loops.