登录shell 和非登录shell

来源:互联网 发布:冒险岛装备数据库 编辑:程序博客网 时间:2024/05/04 10:34

1.前言:

我们知道当在shell里面运行应用程序的时候,表现形式会受到配置参数的影响,最主要的是一些path,或者shell本身的配置。

linux的配置一般分成两种,一种是profile,另一种是rcprofile是和用户和机器配置相关的,比如USERNAMEHOSTNAME或者HOME。而rc则是主要负责一些和路径等和运行时更相关的参数,最主要的是PATH

 

在第一次用户login的时候,就会初始化profile相关的脚本,这就是所谓的login shell当在已经存在的shell里面启动另外一个shell的时候,比如使用"bash"或者"su",启动的这个新shell就会初始化rc相关的脚本。这个shell就称为non-login shell

login shell会执行的脚本通常有 /etc/profile~/.bash_profile

non-login shell会执行的脚本通常有/etc/bashrc (在Ubuntu Jaunty 上是/etc/bash.bashrc)和~/.bashrc

在所有的shell中,子shell继承父shellenv环境变量。但是要注意env的初始创建和shell并没有什么关系。

2.区别:

每次bash作为login shell启动时会执行.bash_profile

主要有有以下几种情形:

     每次登录到服务器时默认启动的shell

     su -l [USER]”时进入的shell

     bash login”进入的shell

 

每次bash作为普通的交互shellinteractive shell)启动时会执行.bashrc

常见的有:

     su [USER]”进入的shell

     直接运行“bash”命令进入的shell

 

注意

     shell脚本中“#!/usr/bin/bash”启动的bash并不执行.bashrc。因为这里的

bash不是interactive shell

     bash作为login shelllogin bash)启动时并不执行.bashrc。虽然该shell

interactive shell,但它不是普通的shell

 

一般.bash_profile里都会调用.bashrc

尽管login bash启动时不会自动执行.bashrc,惯例上会在.bash_profile中显式调用.bashrc

if [ -f ~/.bashrc ]; then

   . ~/.bashrc

fi

3.试验脚本

用以下文件可以很方便的验证以上所述。

-bash-2.05b$ cat .bashrc

echo "in bashrc"

export TEST="rc"

-bash-2.05b$ cat .bash_profile

echo "in bash profile"

-bash-2.05b$ cat test.sh

#!/bin/bash

echo $TEST

bash-2.05b$

from zhenhuaqin.cublog.cn