一、變量介紹
将一些資料需要臨時存放在記憶體中,以待後續使用時快速讀出。
二、變量分類
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檔案中
[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
[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