登陆shell,非登陆shell 以及交互shell和非交互shell

3,494 阅读3分钟

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

non-interactive, non-login shell

When a shell runs a script or a command passed on its command line

我们平时运行的shell脚本,一般是不和用户交互的,这就是一种非交互,非登陆shell.

interactive, non-login shell

在系统已经登陆后,你打开一个终端,或者执行bash 命令新建一个终端窗口,这就是一种交互式的非登陆shell.

login shell 是特殊的情况,我们单独说.

login shell

A login shell is the first process that executes under your user ID when you log in for an interactive session.

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 读取的配置

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

  • inputrc 处理键盘映射
  • /etc/profile.d 下面主要是sh脚本.

这里谈一下/etc/profile和/etc/profile.d的区别

  1. 两个文件都是设置环境变量文件的,/etc/profile是永久的环境变量,是全局变量,/etc/profile.d/是全局脚本,所有用户生效
  2. /etc/profile.d/ 比 /etc/profile好维护,不想要什么变动直接删除/etc/profile.d 下对应的shell脚本即可,不用像/etc/profile需要改动此文件
# 下面以jdk的安装为例
vi  /etc/profile.d/java.sh
#set java environment
JAVA_HOME=/var/mysoft/jdk1.7.0_80 
PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME PATH
#保存退出,然后给java.sh分配权限:
chmod 755 /etc/profile.d/java.sh
#使配置立即生效: 
source /etc/profile.d/java.sh

no login shell 读取的配置

在非登录shell里,只读取 ~/.bashrc (一般会在其中再去读取/etc/bash.bashrc、/etc/bashrc )文件,不同的发行版里面可能有所不同,如RHEL6.3中非登录shell仅执行了“~/.bashrc”文件(没有执行/etc/bashrc),而KUbuntu10.04中却依次执行了/etc/bash.bashrc 和 ~/.bashrc 文件。 对于这些规则,可以直接在相应的配置文件中加一些echo命令来验证其真实性。

区别这两种shell

我们可以用以下方式分别login shell 和 nologin shell:

> echo $0
-bash # "-" is the first character. Therefore, this is a login shell.

> echo $0
bash # "-" is NOT the first character. This is NOT a login shell.

在bash中,你也可以

> shopt login_shell
login_shell     off  # no login 

ssh 一定是个login shell. For Example:

> ssh user@localhost
user@localhost's password:
> echo $0
-bash

参考

unix.stackexchange.com/questions/3…

smilejay.com/2012/10/int…