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.

转载于:https://www.cnblogs.com/hellogc/p/3273373.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值