Linux 中declare命令

 

Linux 中declare命令

 

001、普通测试

[root@PC1 dir1]# ls
[root@PC1 dir1]# echo $var1

[root@PC1 dir1]# var1="hello world"
[root@PC1 dir1]# echo $var1
hello world
[root@PC1 dir1]# var1=100.55
[root@PC1 dir1]# echo $var1
100.55
[root@PC1 dir1]# var1=100
[root@PC1 dir1]# echo $var1
100

 

002、声明变量类型为int型

[root@PC1 dir1]# ls
[root@PC1 dir1]# echo $var1

[root@PC1 dir1]# declare -i var1                 ## 声明变量为整型
[root@PC1 dir1]# var1="hello world"              ## 定义字符串,报错
-bash: hello world: syntax error in expression (error token is "world")
[root@PC1 dir1]# var1=hello_world                ## 无法输出正确值
[root@PC1 dir1]# echo $var1
0
[root@PC1 dir1]# var1=100.555                    ## 定义浮点数,报错
-bash: 100.555: syntax error: invalid arithmetic operator (error token is ".555")
[root@PC1 dir1]# var1=100                        ## 定义整形,可以正常显示
[root@PC1 dir1]# echo $var1
100

 。

 

003、 设置变量为只读

a、

[root@PC1 dir1]# ls
[root@PC1 dir1]# echo $var1

[root@PC1 dir1]# declare -r var1          ## 定义变量为只读
[root@PC1 dir1]# var1=100
-bash: var1: readonly variable
[root@PC1 dir1]# var1="hello world"
-bash: var1: readonly variable
[root@PC1 dir1]# var1=hello_word
-bash: var1: readonly variable
[root@PC1 dir1]# declare -r var1="xxxx"             ## 均无法赋值
-bash: declare: var1: readonly variable

 

b、

 

c、

[root@localhost test]# ls
[root@localhost test]# declare -r var1="hello world"           ## 定义只读变量
[root@localhost test]# echo $var1
hello world
[root@localhost test]# var1=100                                ## 无法给var1变量赋值
-bash: var1: readonly variable
[root@localhost test]# var1="xxx"
-bash: var1: readonly variable
[root@localhost test]# echo $var1
hello world

 .

 

004、declare -x选项:指定的变量会成为环境变量,可供shell以外的程序来使用。

[root@PC1 test2]# var1=100
[root@PC1 test2]# echo $var1
100
[root@PC1 test2]# export -p | grep "var1"
[root@PC1 test2]# declare -x var1=200
[root@PC1 test2]# echo $var1
200
[root@PC1 test2]# export -p | grep "var1"
declare -x var1="200"

 。

 

posted @ 2025-02-22 20:02  小鲨鱼2018  阅读(33)  评论(0)    收藏  举报