Bash Declare Statement

Bash Scripting - Declare Statement Examples

Using the declare statement

The "declare" statement is used to modify the properties of a variable. You can specify whether a variable should be an integer only, read only. The below table indicates some of the available options:

Declaration Type Description
-a Variable is an Array
-f Use function names only
-i Variable is an integer
-p Used to display attributes of variable
-r read only - Makes variables read-only
-t Gives variable the trace attribute
-x Marks each variable for export to subsequent commands via the environment

By using a "+" instead of the "-" switches the attribute off.

Example Declarations using declare

Declare a Variable as an Integer

john@john-desktop:~/scripts$ declare -i MyNumber=123456789
john@john-desktop:~/scripts$ declare -p MyNumber
declare -i MyNumber="123456789"

Display properties of a Variable using -p

john@john-desktop:~/scripts$ declare -p MyNumber
declare -i MyNumber="123456789"

john@john-desktop:~/scripts$ MyString="Land of Linux"
john@john-desktop:~/scripts$ declare -p MyString
declare -- MyString="Land of Linux"

Notice the difference between the integer and a string. The string has the default setting of "--". The integer has the "-i" set. By default all variables are set to "--".

Declare a Variable as Read Only

john@john-desktop:~/scripts$ declare -r rovariable=2468
john@john-desktop:~/scripts$ declare -p rovariable
declare -r rovariable="2468"
john@john-desktop:~/scripts$ rovariable=1357
bash: rovariable: readonly variable

Notice, if you try to change the contents of the read only variable, you will receive an error!.