shell脚本(5)-shell变量

一、变量介绍

将一些数据需要临时存放在内存中,以待后续使用时快速读出。

 

二、变量分类

1、本地变量:

用户私有变量,只有本用户可以使用,保存在家目录下的.bash_profile、.bashrc文件中

[root@localhost test20210724]# ls -a ~/.bash*
/root/.bash_history  /root/.bash_logout  /root/.bash_profile  /root/.bashrc

2、全局变量:

所有用户都可以使用,保存在/etc/profile、/etc/bashrc文件中

[root@localhost test20210724]# ll /etc/profile /etc/bashrc -l
-rw-r--r--. 1 root root 2853 Apr  1  2020 /etc/bashrc
-rw-r--r--. 1 root root 1845 May 20 06:10 /etc/profile

3、用户自定义变量:

用户自定义,比如脚本中的变量

[root@localhost test20210724]# name='baism'
[root@localhost test20210724]# echo $name
baism

 

三、定义变量

1、变量格式:

变量名=值;在shell编程中变量名和等号之间不能有空格

2、变量命名规则:

(1)命名中只能使用英文字母、数字和下划线,首个字符不能以数字开发

(2)中间不能有空格,可以使用下划线

(3)不能使用标点符号

(4)不能使用bash里的关键字(可用help查看保留关键字)

注意:字符串要用单引号或双引号引起来

3、读取变量内容:echo $xx

[root@localhost test20210724]# name="小王"
[root@localhost test20210724]# age=18
[root@localhost test20210724]# echo 小王是$name,而他是$age岁
小王是小王,而他是18岁

4、取消变量:unset

[root@localhost test20210724]# name="小王"
[root@localhost test20210724]# unset name
[root@localhost test20210724]# echo $name

5、定义全局变量export

[root@localhost test20210724]# export gender='male'
[root@localhost test20210724]# echo $gender
male

6、定义永久变量

本地变量:用户私有变量,只有本用户可以使用,保存在家目录下的.bash_profile、.bashrc文件中

全局变量:所有用户都可以使用,保存在/etc/profile、/etc/bashrc文件中

(1)本地变量:

[root@localhost test20210724]# echo name='mrwhite' >> ~/.bash_profile 
[root@localhost test20210724]# tail -1 ~/.bash_profile 
name=mrwhite
[root@localhost test20210724]# echo $name

[root@localhost test20210724]# source ~/.bash_profile 
[root@localhost test20210724]# echo $name
mrwhite

(2)全局变量

[root@localhost test20210724]# echo "export age=30" >> /etc/profile
[root@localhost test20210724]# tail -1 /etc/profile
export age=30
[root@localhost test20210724]# echo $age

[root@localhost test20210724]# source /etc/profile
[root@localhost test20210724]# echo $age
30

 

原文地址:https://www.cnblogs.com/mrwhite2020/p/15017979.html