Linux---Linux環境變量的使用

一、什麼是環境變量

    環境變量是用來存儲關於shell會話和工作環境的信息。

    bash shell中共有兩種類型的環境變量:

          全局變量

          本地變量

(1)全局環境變量

全局環境變量在shell會話和該shell產生的任何子進程中都可見。

查看全局環境變量的命令:

$:printenv
$:echo $HOME

(2)本地環境變量

本地環境變量只是定義他們的本地進程中可見。

set命令顯示特定進程的所有環境變量集

$:set 

注:通過printenv看到的所有全局環境變量都出現了set命令的輸出中。

二、設置環境變量

(1)設置本地環境變量

示例:(只在當前的shell生效)

zc@linux-B7102T76V12HR-2T-N:~$ test=testing
zc@linux-B7102T76V12HR-2T-N:~$ echo $test
testing

(2)設置全局環境變量

通過export命令來完成:

zc@linux-B7102T76V12HR-2T-N:~$ test=testing
zc@linux-B7102T76V12HR-2T-N:~$ echo $test
testing
zc@linux-B7102T76V12HR-2T-N:~$ export test
zc@linux-B7102T76V12HR-2T-N:~$ bash
zc@linux-B7102T76V12HR-2T-N:~$ echo $test
testing

三、移除環境變量

unset命令

$:echo $test
testing
$:unset test
$:echo $test

四、默認的shell環境變量

bash shell提供的與原Unix Bourn shell兼容的環境變量

zc@linux-B7102T76V12HR-2T-N:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

五、設置PATH環境變量

$:echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
$:PATH=$PATH:/home/zc/test
$:echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/zc/test
$:test 
testing

六、定位系統環境變量

        bash處理的啓動文件依賴於啓動bash shell的方法,可採用三種方法來啓動bash shell:

                 在登錄是作爲默認登錄shell

                 作爲非登錄shell的交互式shell

                  作爲非交互式shell運行腳本

(1)登錄shell

         bash shell作爲shell啓動,登錄shell將查找4個不同的啓動文件來處理其中的命令,順序如下:

                 /etc/profile

                 $HOME/.bash_profile

                 $HOME/.bash_login

                 $HOME/.profile

(2)交互式shell

       如果啓動了一個bash shell而沒有登錄系統(比如說,只在CLI提示符中鍵入bash),這就是一個交互式shell。如果bash作爲交互式shell啓動,則它不會處理/etc/profile文件,相反,會檢查用戶HOME目錄中的.bashrc文件。

(3)非交互式shell (不常用)

七、變量數組

環境變量的一個較好的特性就是能夠當做數組使用,數組是能夠保存多個值的變量。

$:mystet=(one two three four five)
$:echo $mytest
one
$:echo ${mytest[2]}
three
$:echo ${mytest[*]}
one two three four five

八、使用命令別名

查看命令別名:

zc@linux-B7102T76V12HR-2T-N:~$ alias -p
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章