declare
-
说明: Set variable values and attributes. Declare variables and give them attributes. If no NAMEs are given,display the attributes and values of all variables.
-
Using
+' instead of
-’ turns off the given attribute.
-Variables with the integer attribute have arithmetic evaluation (see the `let’ command) performed when the variable is assigned a value. -
When used in a function,
declare' makes NAMEs local, as with the
local’ command. The `-g’ option suppresses this behavior. -
declare(别名 typeset)属 Shell 内建命令,用于申明 Shell 变量并设置变量属性,或查看已定义的 Shell 变量和函数。若不加上任何参数,只执行 declare/typeset 则会显示全部的 Shell 变量与函数(与执行 set 指令的效果相同)。
-
用法:
declare [-aAfFgilnrtux] [-p] [name[=value] ...]
;typeset [-aAfFgilrtux] [-p] [name[=value] ...]
选项说明
-a:申明数组变量
-A:申明关联数组,可以使用字符串作为数组索引
-f:仅显示已定义的函数
-F:不显示函数定义
-g:指定变量为全局变量,即使在函数内定义变量
-i:声明整型变量
-l:将变量值的小写字母变为小写
-r:设置只读属性
-t:设置变量跟踪属性,用于跟踪函数进行调试,对于变量没有特殊意义
-u:变量值的大写字母变为大写
-x:将指定的Shell变量换成环境变量
-p:显示变量定义的方式和值
+:取消变量属性,但是 +a 和 +r 无效,无法删除数组和只读属性,可以使用unset删除数组,但是 unset 不能删除只读变量
用法示例
- 数组与关联数组; 显示变量的值;
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -a a_arr=([0]=1 [1]=2)
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -p a_arr
declare -a a_arr=([0]="1" [1]="2")
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -A A_arr=([a]=1 [b]=2)
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -p A_arr
declare -A A_arr=([a]="1" [b]="2" )
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ echo ${a_arr[@]}
1 2
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ echo ${A_arr[@]}
1 2
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ echo ${!A_arr[@]}
a b
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ echo ${!a_arr[@]}
0 1
- 只读变量;类型
readonly
readonly read_only_var="123"
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -r read_only_var="234"
bash: declare: read_only_var: readonly variable
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -r read_only_var2="234"
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare read_only_var2 read_only_var
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -p read_only_var2 read_only_var
declare -r read_only_var2="234"
declare -r read_only_var="123"
- 整型变量:
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -i a=123
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -i b=aaa
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -i a=123.3
bash: declare: 123.3: syntax error: invalid arithmetic operator (error token is ".3")
15116@DESKTOP-9B3MP6T MINGW64 ~/Desktop/tmp
$ declare -p a b
declare -i a="123"
declare -i b="0"
- 其他:
declare -x # 查看所有环境变量
declare -x a # shell变量 a 转换为临时环境变量,供当前Shell会话的其他shell进程使用,退出当前Shell会话则失效
declare +x a # 取消变量shell变量 a为环境变量