Shell 自定义变量

9 篇文章 0 订阅
本文详细介绍了Shell脚本中变量的定义、撤销、声明及其作用域。通过实例展示了局部变量和全局变量的区别,以及如何通过`export`命令将变量设置为全局。还提到了变量命名规则,强调了变量值的赋值方法以及只读变量的特性。最后讨论了Shell变量在子Shell中的行为,指出变量范围是向下传递的,子Shell无法访问其父Shell的变量。
摘要由CSDN通过智能技术生成

Ptw-cwl


基本语法

(1)定义变量:变量名=变量值,注意,=号前后不能有空格

(2)撤销变量:unset 变量名

(3)声明静态变量:readonly 变量,注意:不能 unset

定义变量

[root@pwd ~]# a=test
[root@pwd ~]# echo $a
test
[root@pwd ~]# a=test01
[root@pwd ~]# echo $a
test01
[root@pwd ~]# a=test02
[root@pwd ~]# echo $a
test02
[root@pwd ~]# 

检查变量的作用范围

开启子shell

[root@pwd ~]# bash
[root@pwd ~]# ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
root     11760 11756  0 15:50 pts/1    00:00:00 -bash
root     31308 11760  0 18:27 pts/1    00:00:00 bash
root     31327 31308  0 18:27 pts/1    00:00:00 ps -f
[root@pwd ~]# 

再次查看变量

[root@pwd ~]# echo $a

[root@pwd ~]#

退出子Shell

[root@pwd ~]# exit
[root@pwd ~]# 

查看变量

[root@pwd ~]# echo $a
test02

上面的案例当中看出,变量范围是局部变量,只能再当前shell进种使用(变量在那个shell中声明就只能在那个shell中使用)

声明全局变量

export 变量名

修改为全局变量

[root@pwd ~]# echo $a
test02
[root@pwd ~]# bash
[root@pwd ~]# echo $a

[root@pwd ~]# exit
[root@pwd ~]# export a
[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]# 

注意:在我们回去变量的值的时候可以使用$变量名称,当我们对变量进行操作的时候直接可以使用变量名称

那么我们如果在子shell中修改变量的值会出现什么情况?

[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]# a=test03
[root@pwd ~]# echo $a
test03
[root@pwd ~]# exit
[root@pwd ~]# echo $a
test02
[root@pwd ~]#

如果我们在子Shell中定义变量,并设为全局变量,那么能在主shell中访问到吗?

[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]# a=test03
[root@pwd ~]# echo $a
test03
[root@pwd ~]# exit
[root@pwd ~]# echo $a
test02
[root@pwd ~]#

很显然不能访问,Shell变量的范围是向下的,子Shell只能访问它下面的子Shell,并不能访问它上面的

变量定义规则

(1)变量名称可以由字母、数字和下划线组成,但是不能以数字开头,环境变量名建 议大写。

(2)等号两侧不能有空格

(3)在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算。

(4)变量的值如果有空格,需要使用双引号或单引号括起来

(5)无法撤销只读变量     unset 变量名称删除普通变量。

[root@pwd ~]# a=123
[root@pwd ~]# echo $a
123
[root@pwd ~]# readonly a
[root@pwd ~]# unset a
-bash: unset: a: cannot unset: readonly variable
[root@pwd ~]# 

注意:关闭当前的shell窗口,所有的变量包括全局的、只读的、局部的都会清空。因为这些变量实际上是存储在内存当中的。

Ptw-cwl


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ptw-cwl

谢谢老板的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值