Linux Know-How provides a collection of introductory texts on often needed Linux skills.


Using the declare built-in

Using a declare statement, we can limit the value assignment to variables.

The syntax for declare is the following:

declare OPTION(s) VARIABLE=value

The following options are used to determine the type of data the variable can hold and to assign it attributes:

Table 10-1. Options to the declare built-in

OptionMeaning
-aVariable is an array.
-fUse function names only.
-iThe variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value (see Section 3.4.6).
-pDisplay the attributes and values of each variable. When -p is used, additional options are ignored.
-rMake variables read-only. These variables cannot then be assigned values by subsequent assignment statements, nor can they be unset.
-tGive each variable the trace attribute.
-xMark each variable for export to subsequent commands via the environment.

Using + instead of - turns off the attribute instead. When used in a function, declare creates local variables.

The following example shows how assignment of a type to a variable influences the value.

[bob in ~] declare -i VARIABLE=12

[bob in ~] VARIABLE=string

[bob in ~] echo $VARIABLE
0

[bob in ~] declare -p VARIABLE
declare -i VARIABLE="0"

Note that Bash has an option to declare a numeric value, but none for declaring string values. This is because, by default, if no specifications are given, a variable can hold any type of data:

[bob in ~] OTHERVAR=blah

[bob in ~] declare -p OTHERVAR
declare -- OTHERVAR="blah"

As soon as you restrict assignment of values to a variable, it can only hold that type of data. Possible restrictions are either integer, constant or array.

See the Bash info pages for information on return status.


Last Update: 2010-12-16