← 返回命令列表

Linux command

declare 命令

文本

复制后可按需替换文件名、目录或参数。

常用示例

Declare an integer variable

declare -i [number]=42

Declare a read-only variable

declare -r [CONSTANT]="value"

Declare an indexed array

declare -a [myarray]=([element1] [element2])

Declare an associative array

declare -A [mymap]=([key1]=value1 [key2]=value2)

Export a variable

declare -x [ENVVAR]="value"

Declare lowercase variable

declare -l [lower]="HELLO"

Declare uppercase variable

declare -u [upper]="hello"

Display attributes and value of a variable

declare -p [variable_name]

List all functions

declare -f

说明

declare is a bash builtin that declares variables with specific attributes. While bash allows implicit variable creation, declare provides explicit type declarations and special behaviors. Integer variables (-i) perform arithmetic automatically: `declare -i x; x=5+3` sets x to 8. Arrays require explicit declaration for proper initialization. Read-only variables cannot be changed or unset. In functions, variables are local by default with declare; use -g for global scope. The -n option creates references to other variables, enabling indirect variable access.

参数

-a
Declare indexed array.
-A
Declare associative array (bash 4+).
-f
Display or declare functions.
-F
Display function names only.
-g
Create global variable (in functions).
-i
Declare integer (arithmetic evaluation).
-l
Convert to lowercase on assignment.
-n
Name reference (bash 4.3+).
-r
Make read-only (constant).
-t
Give trace attribute (debugging).
-u
Convert to uppercase on assignment.
-x
Export to environment.
-I
Inherit attributes and value from variable of same name at surrounding scope (bash 5.1+).
-p
Display attributes and values.
+_attr_
Remove attribute.

FAQ

What is the declare command used for?

declare is a bash builtin that declares variables with specific attributes. While bash allows implicit variable creation, declare provides explicit type declarations and special behaviors. Integer variables (-i) perform arithmetic automatically: `declare -i x; x=5+3` sets x to 8. Arrays require explicit declaration for proper initialization. Read-only variables cannot be changed or unset. In functions, variables are local by default with declare; use -g for global scope. The -n option creates references to other variables, enabling indirect variable access.

How do I run a basic declare example?

Run `declare -i [number]=42` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does -a do in declare?

Declare indexed array.