一、變數介紹

將一些資料需要臨時存放在記憶體中,以待後續使用時快速讀出。

二、變數分類

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