declare
Declare variables and/or give them attributes. If no NAMEs are given then display the values of variables.[1]
Documentation
- declare [EN] @ GNU Bash Reference Manual
- bash -c 'help declare'
- man 1 'bash' [EN]
Syntax
declare [PARAMETER ...] [NAME[=VALUE] ...]
Parameters
- -f
- This option will restrict the display to shell functions.[2]
- -F
- This option inhibits the display of function definitions; only the function name and attributes are printed.[2]
- -g
- This option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases.[2]
- -p
- This option will display the attributes and values of each NAME. When -p is used with name arguments, additional options, other than -f and -F, are ignored.
- When -p is supplied without name arguments, declare will display the attributes and values of all variables having the attributes specified by the additional options. If no other options are supplied with -p, declare will display the attributes and values of all shell variables.[2]
- -t
- Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables.[2]
Set attributes
Using + instead of - turns off the attribute instead, with the exceptions that +a and +A may not be used to destroy array variables and +r will not remove the readonly attribute.[2]
Examples
- Show a list of all defined functions
declare -f
- Test if a function exists e.g. my::_cd
if declare -F my::_cd >'/dev/null' 2>&1; then
alias cd='my::_cd'
fi
- Protect variables and functions so that they are not overwritten
bar='bla'
foo() { :; }
declare -r bar
declare -r -f foo
bar='bla'
foo() { :; }
Output:
test.sh: line 7: bar: readonly variable
test.sh: line 8: foo: readonly function
- Test if a variable or a function is writable
PI='3.14159265359'
declare -p 'PI'
if [[ "$(declare -p 'PI')" =~ declare\ -[^\ ]*r ]]; then
echo 'PI is read only'
else
echo 'PI is writable'
fi
declare -r 'PI'
declare -p 'PI'
if [[ "$(declare -p 'PI')" =~ declare\ -[^\ ]*r ]]; then
echo 'PI is read only'
else
echo 'PI is writable'
fi
Output:
declare -- PI="3.14159265359"
PI is writable
declare -r PI="3.14159265359"
PI is not writable