Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 環境變量完整指南:分類、配置文件層級、export 機制與定制最佳實踐

編輯:Linux 教學

環境變量分類

變量作用
PATH可執行文件搜索路徑
HOME當前用戶主目錄
SHELL當前 Shell 類型
LANG/LC_ALL語言/地區設置
PS1/PS2主/次提示符
HISTSIZE歷史命令保存條數
LD_LIBRARY_PATH運行時共享庫搜索路徑
IFS內部字段分隔符

配置文件加載順序與作用域

/etc/profile          # 登錄 Shell,全局環境變量
/etc/bashrc           # 交互式非登錄 Shell,全局別名/函數
~/.bash_profile       # 用戶登錄 Shell,個人環境變量
~/.bashrc             # 用戶交互式非登錄 Shell,個人別名/函數
~/.profile            # 兼容 POSIX 登錄 Shell

原則:環境變量放 profile 類,別名/函數/提示符放 bashrc 類;.bash_profile 通常 source .bashrc。

export 機制實驗

# export1.sh
foo="local only"
export bar="exported"
./export2.sh

# export2.sh
echo "foo=$foo"   # 空行,未導出
echo "bar=$bar"   # 輸出 exported

只有 export 的變量才會傳遞給子 Shell/進程。

定制最佳實踐

  1. 永久生效:編輯 ~/.bash_profile 加 export VAR=value,重新登錄或 source ~/.bash_profile
  2. 臨時生效:當前終端 export VAR=value
  3. 腳本內隔離:腳本首行 #!/bin/bash,內部 export 僅影響子進程
  4. 查看所有:env (環境變量) / set (含 Shell 局部變量)

常見坑點

  • crontab 任務環境極簡,腳本內必須 export PATH=...
  • sudo 默認重置環境,需 sudo -E 或 Defaults env_keep
  • 中文亂碼多因 LANG/LC_ALL 未統一設置為 zh_CN.UTF-8
Copyright © Windows教程網 All Rights Reserved