华为二面被问“Linux系统配置文件”,教你一招怒怼面试官!

159 阅读3分钟

Linux系统配置文件详解

区别


首先先总体看一下区别

============
/etc/profile

此文件为系统的每个用户设置环境信息,对所有用户有效

===========
/etc/bashrc (ubuntu为 /etc/bash.bashrc)

为每一个运行bash shell的用户执行此文件.对所有用户有效

===============
~/.bash_profile (ubuntu为 ~/.profile)

类似/etc/profile,但仅仅针对当前用户有效

=========
~/.bashrc

类似/etc/bashrc,但仅仅针对当前用户有效

==============
~/.bash_logout

当每次退出系统(退出bash shell)时,执行该文件. 

  • Linux的Shell种类众多,常见的有: Bourne Shell(/usr/bin/sh或/bin/sh)、 Bourne Again Shell(/bin/bash)、 C Shell(/usr/bin/csh)、 K Shell(/usr/bin/ksh)、 Shell for Root(/sbin/sh)等等。
  • 不同的Shell语言的语法有所不同,所以不能交换使用。每种Shell都有其特色之处,基本上,掌握其中任何一种 就足够了。在本文中,我们关注的重点是Bash,也就是Bourne Again Shell,由于易用和免费,Bash在日常工作中被广泛使用;同时,Bash也是大多数Linux系统默认的Shell。

login和non login


loginnon login指的是用登录或非登录的方式打开bash shell,不同的方式的读取的配置文件不同,可以归纳为下表:

loginnon login
全局/etc/profile/etc/bashrc
单用户~/.bash_profile~/.bashrc

执行顺序


登录Linux时执行

在 刚登录Linux时,首先启动 /etc/profile 文件,然后再启动用户目录下的 ~/.bash_profile

再执行用户的bash设置

如果 ~/.bash_profile文件存在的话,会执行用户的 ~/.bashrc文件。

#if running bash

if [ -n "$BASH_VERSION" ]; then

	# include .bashrc if it exists

    if [ -f "$HOME/.bashrc" ]; then
    	. "$HOME/.bashrc"
    fi
fi

同样~/.bashrc中,一般还会在文件的前面有以下代码,来执行/etc/bashrc

if [ -f /etc/bashrc ] ; then
 . /etc/bashrc

所以,~/.bashrc会调用 /etc/bashrc文件。最后,在退出shell时,还会执行 ~/.bash_logout文件。

执行顺序为:

  • /etc/profile
  • ~/.bash_profile | ~/.bash_login | ~/.profile
  • ~/.bashrc
  • /etc/bashrc
  • ~/.bash_logout

区别和联系


  • 在 /etc目录是系统级(全局)的配置文件,当在用户主目录下找不到~/.bash_profile 和~/.bashrc时,就会读取这两个文件。
  • /etc/profile 中设定的变量(全局)的可以作用于任何用户,而 ~/.bashrc 中设定的变量(局部)只能继承 /etc/profile 中的变量,他们是“父子”关系。
  • ~/.bash_profile 是交互式、login 方式进入 bash 运行的; ~/.bashrc 是交互式 non-login 方式进入 bash 运行的。通常二者设置大致相同,所以通常前者会调用后者。设置生效:可以重启生效,也可以使用命令:source。
  • ~/.bash_history是bash shell的历史记录文件,里面记录了你在bash shell中输入的所有命令。可通过HISSIZE环境变量设置在历史记录文件里保存记录的条数。

其他


下面是几个例子:

  1. 图形模式登录时,顺序读取:/etc/profile~/.profile
  2. 图形模式登录后,打开终端时,顺序读取:/etc/bash.bashrc~/.bashrc
  3. 文本模式登录时,顺序读取:/etc/bash.bashrc/etc/profile~/.bash_profile
  4. 从其它用户su到该用户,则分两种情况: (1)如果带-l参数(或-参数,–login参数),如:su -l username,则bash是lonin的,它将顺序读取以下配置文件:/etc/bash.bashrc/etc/profile~ /.bash_profile。 (2)如果没有带-l参数,则bash是non-login的,它将顺序读取:/etc/bash.bashrc~/.bashrc
  5. 注销时,或退出su登录的用户,如果是longin方式,那么bash会读取:~/.bash_logout
  6. 执行自定义的shell文件时,若使用“bash -l a.sh”的方式,则bash会读取行:/etc/profile~/.bash_profile,若使用其它方式,如:bash a.sh, ./a.sh,sh a.sh(这个不属于bash shell),则不会读取上面的任何文件。

分类: [Linux] 标签: [Linux]

在这里插入图片描述