背景
-
工作中,发现很多同事对Linux的env感觉困惑,其实是很简单的东西。
例如:ssh登陆机器后无法看到一些env;同事很疑惑; -
下面结合bash来讲解一下env和bash/shell
概念:
- Bash是一种UNIX shell,就是命令行解释器,也是一种脚本语言;生于1989年,目的是代替Bourne Shell;
- Bourne Shell:作者是 Stephen Bourne,bell实验室的。早期的shell实现,生于1976年;
- shell:就是UI,连接着人类和机器。shell使用CLI和GUI,他是一种概念,有多种实现;
- Bourne Shell:作者是 Stephen Bourne,bell实验室的。早期的shell实现,生于1976年;
env
- 作用:1)shell给子进程通信 ,2)shell脚本内存储临时变量
- 初始化:init进程初始化脚本负责初始化
- 继承:默认继承父进程的env,父进程可以在fork和exec之间显示改变环境变量;
- PS1: 提示符的格式:[\u@\h \W]$
- $LD_LIBRARY_PATH: .so的位置
启动脚本 执行顺序
1.When started as an interactive login shell[edit]
Bash reads and executes /etc/profile (if it exists). (Often this file calls /etc/bash.bashrc.)
After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile in that order, and reads and executes the first one that exists and is readable.
2.When a login shell exits[edit]
Bash reads and executes ~/.bash_logout (if it exists).
3.When started as an interactive shell (but not a login shell)[edit]
Bash reads and executes /etc/bash.bashrc and then ~/.bashrc (if it exists). This may be inhibited by using the --norcoption. The --rcfile file option forces Bash to read and execute commands from file instead of ~/.bashrc.
兼容性
~/.bash_profile 是兼容Bourne Shell的,内容如下:
[ -r ~/.profile ] && . ~/.profile # set up environment, once, Bourne-sh syntax only
if [ -n "$PS1" ] ; then # are we interactive?
[ -r ~/.bashrc ] && . ~/.bashrc # tty/prompt/function setup for interactive shells
[ -r ~/.bash_login ] && . ~/.bash_login # any at-login tasks for login shell only
fi # End of "if" block
结论
- 子进程默认会继承父进程的env
- 交互式的shell会默认执行一些启动脚本,登陆shell和非登陆shell有些不同,如果要读取env,将env写入启动脚本里。不同的bash进程env不会共享的。
- login shell: 一般ps -ef|grep bash后看到一个小尾巴~bash
参考:https://en.wikipedia.org/wiki/Bash_(Unix_shell)