Shell的环境变量
shell变量的作用域
- 全局变量:当前 shell 进程中使用的变量,无前缀词修饰直接赋值的变量,如 FOO=bar
- 环境变量:可以在子进程中使用的变量,使用 export 导出,如 export FOO=bar
- 局部变量:使用 local 修饰,只能在函数内部使用。注意,bash 支持 local ,但 POSIX shell (sh)不一定支持。
登录式shell和非登录式shell
- 登录式shell
包含两种情况:
- 直接通过终端输入帐号密码登录
- 使用
su - username
切换的用户
登录式shell的配置文件以 /etc/profile
为入口,然后嵌套引入其他配置文件,常见的加载顺序通常为:(/etc/profile -> /etc/bash.bashrc -> /etc/profile.d/*.sh) -> ~/.bash_profile -> ~/.bashrc [-> /etc/bashrc]
- 非登录式shell
包含这几种情况:
- su username
- 图形界面下打开的终端
- 执行脚本
- 其他任何bash实例
配置文件执行顺序:~/.bashrc -> /etc/bashrc -> /etc/profile.d/*.sh
检查环境变量的几个命令
- set:输出所有变量
- declare:同上
- env:只显示全局变量
- export:只显示和设置环境变量
配置文件说明
系统级
-
/etc/profile
:用户登录时操作系统定制用户环境使用的第一个文件,对所有用户生效。该文件一般是调用 /etc/bash.bashrc 和 /etc/profile.d/*.sh 。 -
/etc/environment
:用户登录时操作系统使用的第二个文件,系统在读取用户 profile 文件前设置 PATH 等环境变量。
用户级(位于家目录下)
-
~/.profile
,~/.<shell>_profile
,~/.<shell>_login
:Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode. -
~/.<shell>rc
:Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode. -
~/.pam_environment
:List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables includingHOME
orPATH
so it has limited use. Used by PAM. -
~/.xprofile
:This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.