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

← All Bash builtins · Linux commands