bash变量

本文详细介绍了Bash shell中的变量类型,包括自定义变量、环境变量、位置变量和预定义变量。讲解了如何定义、引用、查看和取消变量,以及变量的作用范围。此外,还阐述了变量赋值的不同方式,如显式赋值和从键盘读入。文章深入探讨了强引用、弱引用和命令替换的概念,以及变量的整数和小数运算方法,包括expr、$( )、$[ ]和let命令。最后,提到了变量值的截断、替换和索引切片操作,帮助读者全面掌握Bash中的变量处理技巧。
摘要由CSDN通过智能技术生成

在shell中,变量大部分情况下不需要声明,可以直接赋值;默认值是字符串类型。变量名必须以字符或下划线_开头,且区分大小写。

1、变量类型:

1.1、自定义变量
1.1.1、定义变量
    变量名=变量值
1.1.2、引用变量
$变量名  或
${变量名}  变量名被括号括起来可以避免在一些情况下引起歧义。
1.1.3、查看变量
echo $变量名 ${变量名}
set | grep 变量名
set 显示所有变量,包括自定义变量和环境变量
1.1.4、取消变量
unset 变量名
1.1.5、变量作用范围
当前shell环境
1.1.6、实例
##定义变量
[root@centos6 ~]# a=666
[root@centos6 ~]# 
[root@centos6 ~]# echo $a
666
[root@centos6 ~]# echo ${a}
666
[root@centos6 ~]# 
##引起歧义,导致变量a没有被显示
[root@centos6 ~]# echo $ab

##加{}避免歧义,变量显示正常
[root@centos6 ~]# echo ${a}b
666b
[root@centos6 ~]# 
[root@centos6 ~]# set|grep ^a=
a=666
[root@centos6 ~]# vi test.sh
[root@centos6 ~]# cat test.sh
#!/bin/bash

echo $a
##执行shell脚本,在子shell执行,变量值没有显示
[root@centos6 ~]# ./test.sh

[root@centos6 ~]# 
##在当前shell执行脚本,显示变量值
[root@centos6 ~]# . ./test.sh
666
[root@centos6 ~]# 
##取消变量
[root@centos6 ~]# unset a
[root@centos6 ~]# 
[root@centos6 ~]# echo $a
1.2、环境变量
1.2.1、定义变量
    export 变量名=变量值
    export 自定义变量名
1.2.2、引用变量
$变量名  或
${变量名}  变量名被括号括起来可以避免在一些情况下引起歧义。
1.2.3、查看变量
echo $变量名 ${变量名}
set | grep 变量名
env |grep 变量名
env 显示所有环境变量
1.2.4、取消变量
unset 变量名
1.2.5、变量作用范围
当前shell和子shell环境
1.2.6、实例
[root@centos6 ~]# a=666
[root@centos6 ~]# 
##定义环境变量
[root@centos6 ~]# export a
[root@centos6 ~]# export bb="test env"
[root@centos6 ~]# 
##查看环境变量
[root@centos6 ~]# echo $a $bb
666 test env
[root@centos6 ~]# 
[root@centos6 ~]# vi test.sh
[root@centos6 ~]# cat test.sh
#!/bin/bash

echo $a
echo $bb

[root@centos6 ~]# 
## 在子shell中查看变量
[root@centos6 ~]# ./test.sh
666
test env
[root@centos6 ~]# 
##在当前shell中查看变量
[root@centos6 ~]# . ./test.sh
666
test env
[root@centos6 ~]# 
##取消变量
[root@centos6 ~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值