三種設定層級與生效範圍
| 方法 | 指令/檔案 | 生效範圍 | 持久性 |
| 1. 命令列暫時修改 |
PATH=$PATH:/new/path |
當前 Shell 進程及其子進程 |
登出/關閉終端機即失效 |
| 2. 系統級永久修改 |
vi /etc/profile |
所有使用者 |
永久,需重新登入或 source /etc/profile |
| 3. 使用者級永久修改 |
vi ~/.bash_profile |
僅當前使用者 |
永久,需重新登入或 source ~/.bash_profile |
關鍵細節
- 等號兩邊不可有空格:
PATH=$PATH:/path,非 PATH = $PATH:/path。
- 立即生效技巧:修改
/etc/profile 或 ~/.bash_profile 後,執行 source /etc/profile 或 ./.bash_profile(注意前面有點)。不可用 sh /etc/profile,因會啟動子 Shell,環境變數不會傳回父 Shell。
環境設定檔架構總覽
| 類型 | 登入 Shell (Login Shell) | 非登入 Shell (Interactive Non-login) |
| 系統級 | /etc/profile | /etc/bashrc |
| 使用者級 | ~/.bash_profile | ~/.bashrc |
登入 Shell:使用者輸入帳密登入、或 bash --login。
非登入 Shell:已登入後開新終端機分頁、執行 bash、執行 Shell 腳本。
實戰範例:新增 Apache 二進制目錄
# 1. 臨時
PATH=$PATH:/etc/apache/bin
# 2. 系統級永久
echo 'PATH=$PATH:/etc/apache/bin' >> /etc/profile
source /etc/profile
# 3. 使用者級永久
echo 'PATH=$PATH:/etc/apache/bin' >> ~/.bash_profile
source ~/.bash_profile