Библиотека сайта rus-linux.net
As we already saw, Bash understands many different kinds of variables or parameters. Thus far, we haven't bothered much with what kind of variables we assigned, so our variables could hold any value that we assigned to them. A simple command line example demonstrates this:
There are cases when you want to avoid this kind of behavior, for instance when handling telephone and other numbers. Apart from integers and variables, you may also want to specify a variable that is a constant. This is often done at the beginning of a script, when the value of the constant is declared. After that, there are only references to the constant variable name, so that when the constant needs to be changed, it only has to be done once. A variable may also be a series of variables of any type, a so-called array of variables (
Using a declare statement, we can limit the value assignment to variables.
The syntax for declare is the following:
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
|Variable is an array.|
|Use function names only.|
|The variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value (see Section 3.4.6).|
|Display the attributes and values of each variable. When |
|Make variables read-only. These variables cannot then be assigned values by subsequent assignment statements, nor can they be unset.|
|Give each variable the trace attribute.|
|Mark each variable for export to subsequent commands via the environment.|
+ 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.
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:
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.
In Bash, constants are created by making a variable read-only. The readonly built-in marks each specified variable as unchangeable. The syntax is:
The values of these variables can then no longer be changed by subsequent assignment. If the
-f option is given, each variable refers to a shell function; see Chapter 11. If
-a is specified, each variable refers to an array of variables. If no arguments are given, or if
-p is supplied, a list of all read-only variables is displayed. Using the
-p option, the output can be reused as input.
The return status is zero, unless an invalid option was specified, one of the variables or functions does not exist, or
-f was supplied for a variable name instead of for a function name.