Linux declare command
The Linux declare command is used to declare shell variables.
declare is a shell command. In its first syntax it can declare variables and set their attributes ([rix] are the variable attributes); in its second syntax it can display shell functions. Without any arguments, it shows all shell variables and functions (the same effect as running the set command).
Syntax
declare [+/-][rxi][变量名称=设置值] 或 declare -f
Parameter Description:
- +/- "-" is used to specify a variable's attribute, while "+" removes the attribute set on a variable.
- -f Display functions only.
- r Set a variable as read-only.
- x The specified variable becomes an environment variable, usable by programs outside the shell.
- i [assigned value] can be a number, a string, or an expression.
Example
Declare an integer variable
Example
declare -i ab // declare an integer variable
ab=56 // change the variable's value
echo $ab // display the variable's value
56
Change a variable's attribute
Example
declare -i ef // declare an integer variable
ef=1 // variable assignment (integer value)
echo $ef // display the variable's value
1
ef="wer" // variable assignment (text value)
echo $ef
0
declare +i ef // remove the variable's attribute
ef="wer"
echo $ef
wer
Set a variable as read-only
Example
declare -r ab // set the variable as read-only
ab=88 // change the variable's value
-bash: ab: read-only variable
echo $ab // display the variable's value
56
Declaring Array Variables
Example
declare -a cd='([0]="a" [1]="b" [2]="c")' // declare an array variable
echo ${cd[1]}
b
//
Display a variable's value
echo ${cd[@]} // display the entire array variable's contents
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
}
Linux Command Reference