From help declare
:
Options which set attributes:
-a to make NAMEs indexed arrays (if supported)
-A to make NAMEs associative arrays (if supported)
-i to make NAMEs have the `integer' attribute
-l to convert the value of each NAME to lower case on assignment
-n make NAME a reference to the variable named by its value
-r to make NAMEs readonly
-t to make NAMEs have the `trace' attribute
-u to convert the value of each NAME to upper case on assignment
-x to make NAMEs export
Note: declare
can also be used for functions.
Each of these attributes has one or several uses:
-a
- to make NAMEs indexed arrays (if supported)
This is not entirely necessary because setting a parameter as an array will automatically declare it as an indexed array. Using this could make your code more obvious and readable.
-A
- to make NAMEs associative arrays (if supported)
AFAIK this is entirely necessary as attempting to set an associative array without first declaring it as such will result in an indexed array.
$ assoc=([foo]=bar)
$ declare -p assoc
declare -a assoc=([0]="bar")
$ unset assoc
$ declare -A assoc
$ assoc=([foo]=bar)
$ declare -p assoc
declare -A assoc=([foo]="bar" )
-i
- to make NAMEs have the `integer' attribute
Useful if you want to ensure your parameter can only hold integers. This also allows you to perform arithmetic expansion on assignment.
$ declare -i a
$ a=foo
$ echo $a
0
$ a=1+1
$ echo $a
2
-l
- to convert the value of each NAME to lower case on assignment
Will ensure that the value of your parameters will always be all lowercase. This is a pretty cool feature that I was unaware of and will probably use in the future. It eliminates the need for complex parameter expansion or using a separate utility like tr
$ declare -l foo=Bar
$ echo $foo
bar
-n
- make NAME a reference to the variable named by its value
Like an indirect reference. This could eliminate the use of eval
in a lot of scripts.
$ a=foo
$ declare -n b=a
$ echo $b
foo
-r
- to make NAMEs readonly
This is a good feature. It could be especially useful for shell/environmental variables that you want to set once and ensure are not changed
$ declare -r foo=bar
$ echo $foo
bar
$ foo=baz
-bash: foo: readonly variable
-t
- to make NAMEs have the `trace' attribute
I'm unsure about this one. I think it may only apply to functions.
-u
- to convert the value of each NAME to upper case on assignment
Similar to -l
but opposite
$ declare -u foo=bAr
$ echo $foo
BAR
-x
- to make NAMEs export
Just another way to export variables to the environment.