Typed Variables

So far we’ve seen how bash variables can be assigned textual values. Variables can also have other attributes, including being read only and being of type integer.

You can set variable attributes with the declare built-in. [80] Table 6.1 summarizes the available options with declare. [81]A - turns the option on, while + turns it off.

Table 6-1. Declare Options

Option Meaning
-a The variables are treated as arrays
-f Use function names only
-F Display function names without definitions
-i The variables are treated as integers
-r Makes the variables read-only
-x Marks the variables for export via the environment

Typing declare on its own displays the values of all variables in the environment. The -f option limits this display to the function names and definitions currently in the environment. -F limits it further by displaying only the function names.

The -a option declares arrays—a variable type that we haven’t seen yet, but will be discussed shortly.

The -i option is used to create an integer variable, one that holds numeric values and can be used in and modified by arithmetic operations. Consider this example:

$ val1=12 val2=5
$ result1=val*val2
$ echo $result1
val1*val2
$
$ declare -i val3=12 val4=5
$ declare -i result2
$ result2=val3*val4
$ echo $result2
60

In the first example, the variables are ordinary shell variables and the result is just the string “val1*val2”. In the second example, all of the variables have been declared as type integer. The variable ...

Get Learning the bash Shell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.