bash 和 環境變量env

背景

  • 工作中,發現很多同事對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,他是一種概念,有多種實現;

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