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
复制代码

 

posted @   Mrwhite86  阅读(141)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示