• login shell与non-login shell的区别


    Bash应该是我们每天日常工作接触最多的东西了,就像我们最忠实的朋友,我们有必要了解一下这位朋友的“习性”。

    Bash有几种不同的运行模式,login shell与non-login shell,interactive shell与non-interactive shell(比如执行shell脚本)。这两种分类方法是交叉的,也就是说一个login shell可能是一个interactive shell,也可能是个non-interactive shell。

    在下列情况下,我们可以获得一个login shell:

    1. 登录系统时获得的顶层shell,无论是通过本地终端登录,还是通过网络ssh登录。这种情况下获得的login shell是一个交互式shell。
    2. 在终端下使用--login选项调用bash,可以获得一个交互式login shell。
    3. 在脚本中使用--login选项调用bash(比如在shell脚本第一行做如下指定:#!/bin/bash --login),此时得到一个非交互式的login shell。
    4. 使用"su -"切换到指定用户时,获得此用户的login shell。如果不使用"-",则获得non-login shell。

    login shell与non-login shell的主要区别在于它们启动时会读取不同的配置文件,从而导致环境不一样。login shell启动时首先读取/etc/profile全局配置,然后依次查找~/.bash_profile、~/.bash_login、~/.profile三个配置文件,并且读取第一个找到的并且可读的文件。login shell退出时读取并执行~/.bash_logout中的命令。

    交互式的non-login shell启动时读取~/.bashrc资源文件。非交互式的non-login shell不读取上述所有配置文件,而是查找环境变量BASH_ENV,读取并执行BASH_ENV指向的文件中的命令。

    如果使用命令"sh"调用bash,bash会尽可能保持向后兼容。作为login shell启动时,bash依次读取/etc/profile和~/.profile配置文件。作为non-login shell启动时,bash读取环境变量ENV指向的文件。

    通常我们要定制一些配置时,将配置写在~/.bashrc中,然后在~/.bash_profile中读取~/.bashrc,这样可以保证login shell和交互式non-login shell得到相同的配置。至于/etc/profile就不要轻易去改啦,毕竟会影响系统全局的配置。

    下面做个简单的实验来验证上面的描述。在~/.bash_profile中设置如下变量:

    lshell="login shell will see this message"

    分别启动一个交互式non-login shell和交互式login shell,查看lshell变量:

    [sw@gentoo ~]$ bash
    [sw@gentoo ~]$ echo $lshell
    
    [sw@gentoo ~]$ exit
    exit
    [sw@gentoo ~]$ bash --login
    [sw@gentoo ~]$ echo $lshell
    login shell will see this message
    [sw@gentoo ~]$ exit
    logout

    可见non-login shell并没有读取~/.bash_profile,login shell读取了,与上面的描述相符。

    References
    1. Linux man page.

  • 相关阅读:
    ActiveMQ之Topic
    ActiveMQ之Queue
    ActiveMQ.xml文件的主要配置
    koa/redux middleware 深入解析
    js在工作中遇到的一些问题
    rxjs-流式编程
    端到端测试工具--testcafe
    js match函数注意
    深入js正则
    滚动联动-单独滚动与文档滚动
  • 原文地址:https://www.cnblogs.com/hellogc/p/3273373.html
Copyright © 2020-2023  润新知