Linux declare Command
The declare
command in Linux is used to declare shell variables.
declare
is a shell command. In the first syntax, it can be used to declare variables and set their attributes ([rix] being the attributes of the variable). In the second syntax, it can be used to display shell functions. If no parameters are added, it will display all shell variables and functions (the same effect as executing the set
command).
Syntax
declare [+/-][rxi][variable_name=value] or declare -f
Parameter Description:
+/- "-" is used to specify the attributes of a variable, "+" is used to unset the attributes of a variable.
-f Displays only functions.
r Sets the variable as read-only.
x The specified variable becomes an environment variable, available for use by programs outside the shell.
i [value] can be a number, string, or expression.
Examples
Declare an integer variable
Example
# declare -i ab //Declare an integer variable
# ab=56 //Change variable content
# echo $ab //Display variable content
56
Change variable attributes
Example
# declare -i ef //Declare an integer variable
# ef=1 //Variable assignment (integer value)
# echo $ef //Display variable content
1
# ef="wer" //Variable assignment (text value)
# echo $ef
0
# declare +i ef //Unset variable attributes
# ef="wer"
# echo $ef
wer
Set variable as read-only
Example
# declare -r ab //Set variable as read-only
# ab=88 //Attempt to change variable content
-bash: ab: readonly variable
# echo $ab //Display variable content
56
Declare an array variable
Example
# declare -a cd='([0]="a" [1]="b" [2]="c")' //Declare an array variable
# echo ${cd[1]}
b //Display variable content
# echo ${cd[@]} //Display entire array variable content
a b c
Display functions
Example
# declare -f
command_not_found_handle ()
{
if [ -x /usr/lib/command-not-found ]; then
/usr/bin/python /usr/lib/command-not-found -- $1;
return $?;
else
if [ -x /usr/share/command-not-found ]; then
/usr/bin/python /usr/share/command-not-found -- $1;
return $?;
else
return 127;
fi;
fi
}