declare
The bash builtin that creates variables with attributes: -i integer, -r read-only, -a array, -A associative array, -n name reference, and -p to print.
In more detail
Inside a function, declare makes the variable local just as local does. declare -p name shows exactly how a variable is set, including its attributes, which helps when debugging arrays.
Examples
declare -A ownerdeclare -p filesRelated terms
- local variable — A variable that exists only inside one function call and cannot be seen or changed from outside it.
- readonly builtin — The builtin that makes a variable unchangeable for the rest of the shell's life, used for constants.
- associative array — A bash 4 array indexed by strings instead of numbers, declared with declare -A.
- nameref — A bash 4.3 variable declared with declare -n or local -n that acts as another name for a variable named by its value.
Taught in
- Which Shell Am I In, And Getting Bash Five — Bash Scripting & Command Line Automation
- Functions, local And declare — Bash Scripting & Command Line Automation
- set -e, set -u And pipefail: Promises And Traps — Bash Scripting & Command Line Automation
- Style That Prevents Bugs — Bash Scripting & Command Line Automation
- eval, And What To Use Instead — Bash Scripting & Command Line Automation