Associating attributes with variables
The typeset command lets you associate attributes with
shell variables. This process is analogous to declaring the type of
a variable in a conventional programming language. For example:
typeset –i8 y
says that y
is an octal integer. In this way, you
can make sure that arithmetic with y
is always performed
in base 8 rather than the usual base 10.Other attributes may specify how the variable's value is displayed
when the variable is expanded. Attributes of this kind are:
- –Ln
- The value should always be displayed with n characters, left-justified within that space.
- –Rn
- The value should always be displayed with n characters, right-justified within that space.
- –RZn
- The value should always be displayed with n characters, right-justified and with enough leading zeros to fill out the rest of the space.
- –Zn
- The same as -RZn.
- –LZn
- The value should always be displayed with n characters, left-justified and with leading zeros stripped off.
All of these options may lead to truncation of a value that is longer than the specified length.
You can use the –u attribute of typeset for variables with string values. Then whenever such a variable is assigned a new value, all lowercase letters in the value are automatically converted to uppercase. Similarly, the –l attribute specifies that whenever a variable is assigned a new value, all uppercase letters in the value are automatically converted to lowercase.
The read-only attribute –r is useful when a variable
is marked for export. The command:
typeset –r name
says
that the variable name cannot be changed from its present
value. Then subsequent commands cannot change this value. You can
also use the format:
typeset –r name=value
which
sets the variable to the given value and marks it read-only so that
the value cannot be changed.