00. 目录
01. 命令概述
declare命令用于定义shell变量,但declare定义的变量仅能在当前shell环境中起作用,切换shell环境后将无效。
declare命令用于声明和显示已存在的shell变量。当不提供变量名参数时显示所有shell变量。declare命令若不带任何参数选项,则会显示所有shell变量及其值。declare的功能与typeset命令的功能是相同的。
02. 命令格式
用法:declare [选项] [参数]
- 1
03. 常用选项
-a 声明数组变量
-f 仅显示函数
-F 不显示函数定义
-i 先计算表达式,把结果赋给所声明变量
-p 显示给定变量的定义的方法和值,当使用此选项时,其他的选项将被忽略
-r 定义只读变量
-x 将指定的Shell变量转换成环境变量
- 1
- 2
- 3
- 4
- 5
- 6
- 7
04. 参考示例
4.1 显示已定义的变量
[root@localhost ~]# declare
- 1
- 2
4.2 定义新的Shell变量
[root@localhost ~]# declare AA="dengjin"
[root@localhost ~]# echo $AA
dengjin
[root@localhost ~]#
- 1
- 2
- 3
- 4
4.3 先计算表达式,把结果赋给所声明变量
[root@localhost ~]# declare -i var=100+300
[root@localhost ~]# echo $var
400
[root@localhost ~]#
- 1
- 2
- 3
- 4
4.4 显示变量var1和var2的定义
[root@localhost ~]# declare -p var AA
declare -i var="400"
declare -i AA="dengjin"
[root@localhost ~]#
- 1
- 2
- 3
- 4
4.5 显示所有的环境变量
[root@localhost ~]# declare -x
declare -x CPLUS_INCLUDE_PATH=":/opt/instantclient_11_2/sdk/include"
declare -x HISTCONTROL="ignoredups"
declare -x HISTSIZE="1000"
declare -x HOME="/root"
declare -x HOSTNAME="localhost.localdomain"
declare -x LANG="zh_CN.UTF-8"
declare -x LD_LIBRARY_PATH=":/opt/instantclient_11_2"
declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s"
declare -x LIBRARY_PATH=":/opt/instantclient_11_2"
declare -x LOGNAME="root"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
4.6 声明整数型变量
[deng@localhost ~]$ declare -i AA
[deng@localhost ~]$ AA=33
[deng@localhost ~]$ echo $AA
33
[deng@localhost ~]$ AA="hello icast"
-bash: hello icast: 表达式中有语法错误 (错误符号是 "icast")
[deng@localhost ~]$ AA=44
[deng@localhost ~]$
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
4.7 取消变量的属性
[deng@localhost ~]$ declare +i AA
[deng@localhost ~]$ AA="hello dengjin"
[deng@localhost ~]$ echo $AA
hello dengjin
[deng@localhost ~]$
- 1
- 2
- 3
- 4
- 5
4.8 设置变量为只读
[deng@localhost ~]$ declare -r var=33
[deng@localhost ~]$ echo $var
33
[deng@localhost ~]$ var=99
-bash: var: 只读变量
[deng@localhost ~]$
- 1
- 2
- 3
- 4
- 5
- 6
4.9 声明数组变量
[deng@localhost ~]$ declare -a cd='([0]="aa" [1]="bb" [2]="cc")'
[deng@localhost ~]$ echo ${cd[@]}
aa bb cc
[deng@localhost ~]$
- 1
- 2
- 3
- 4
4.10 声明环境变量
[deng@localhost ~]$ declare -x AA=33
[deng@localhost ~]$ bash
[deng@localhost ~]$ echo $AA
33
[deng@localhost ~]$
- 1
- 2
- 3
- 4
- 5
- 6
评论记录:
回复评论: