在我阅读bash手册页时,只应在以交互方式运行shell时执行.bashrc。该联机帮助页将交互式定义为:
交互式shell是在没有非选项参数的情况下启动的 并且没有-c选项,其标准输入和错误都是 连接到终端(由isatty(3)确定),或者一个已启动 使用-i选项。 PS1已设置且$ - 如果bash为,则包含i 交互式,允许shell脚本或启动文件来测试它 状态。
然而,使用ssh执行命令也会导致运行.bashrc,这与我期望的相反,因为该命令不是以交互方式运行的。所以,这种行为看起来像一个bug,但它似乎在我尝试过的Red Hat和bash的所有版本上都很普遍。有人可以解释为什么这种行为是正确的吗?
还有一点:即使运行.bashrc,$-
和$PS
也会被设置,好像shell是非交互式的(正如我所料)。
$ grep USER /etc/passwd
USER:x:UID:GID:UNAME:/home/USER:/bin/bash
$ cat ~/.bashrc
echo bashrc:$-,$PS1
$ bash -c 'echo $-'
hBc
$ ssh localhost 'echo $-' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,
hBc
$ ssh localhost 'ps -ef | grep $$' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,
USER 28296 28295 0 10:04 ? 00:00:00 bash -c ps -ef | grep $$
USER 28297 28296 0 10:04 ? 00:00:00 ps -ef
USER 28298 28296 0 10:04 ? 00:00:00 grep 28296
我目前正在通过测试.bashrc中的[[ $- = *i* ]]
来解决这个问题,但似乎我不应该这样做。
一个示例服务器,在我的主目录中没有包含.bashrc(和.ssh)的其他文件,具有以下配置:
$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.7 (Tikanga)
$ bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
我试过的bash版本:3.00.15,3.1.17,3.2.25,4.1.2(后者在Red Hat 6.3上)。
答案 0 :(得分:3)
来自Bash manual:
Bash尝试确定何时将其标准输入连接到网络连接,如远程shell守护程序(通常为
rshd
或安全shell守护程序sshd
)执行时。如果Bash确定它以这种方式运行,它将从~/.bashrc
读取并执行命令,如果该文件存在且可读的话。如果作为sh调用它将不会这样做。--norc
选项可用于禁止此行为,--rcfile
选项可用于强制读取另一个文件,但rshd
通常不会使用这些选项调用shell或允许他们被指定。
默认Debian bashrc
框架中的解决方法是将以下内容放在.bashrc
的顶部:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return