shell中的变量

2019-03-26  本文已影响0人  城堡下的晚祷

1.系统变量

(1)$HOME 显示当前用户的家目录

/root

(2)$PWD显示当前目录

[root@localhost shelldata]# echo $PWD
/home/yzl/shelldata

(3)$SHELL显示默认的shell解析器

[root@localhost shelldata]# echo $SHELL
/bin/bash

(4)$USER显示当前用户

[root@localhost shelldata]# echo $USER
root

2.自定义变量

(1)语法:

定义变量:变量=值

[root@localhost shelldata]# echo $A

[root@localhost shelldata]# A=2
[root@localhost shelldata]# echo $A
2
[root@localhost shelldata]# A=3
[root@localhost shelldata]# echo $A
3

撤销变量:unset 变量名

[root@localhost ~]# A=4
[root@localhost ~]# echo $A
4
[root@localhost ~]# unset A
[root@localhost ~]# echo $A

声明静态变量 readonly 变量=值

[root@localhost ~]# readonly B=5
[root@localhost ~]# echo $B
5
[root@localhost ~]# B=8
-bash: B: readonly variable
[root@localhost ~]# unset B
-bash: unset: B: cannot unset: readonly variable

静态变量不可以被重新赋值或者unset。

可以把变量提升为全局环境变量,可供其他Shell程序使用 export 变量名

编辑helloworld.sh的内容如下,需要输出变量hello123的值:

[root@localhost shelldata]# cat helloworld.sh 
#!/bin/bash
echo "hello world"
echo $hello123

在bash文件外部定义变量hello123并赋值,运行bash脚本:

[root@localhost shelldata]# hello123="this is hello123"
[root@localhost shelldata]# ./helloworld.sh 
hello world

将hello123提升为全局环境变量,再次运行脚本:

[root@localhost shelldata]# export hello123
[root@localhost shelldata]# ./helloworld.sh 
hello world
this is hello123
(2)变量定义规则
[root@localhost ~]# C=1+2
[root@localhost ~]# echo $C
1+2
[root@localhost ~]# D='1 hello'
[root@localhost ~]# echo $D
1 hello
上一篇 下一篇

猜你喜欢

热点阅读