bash seems to ignore BASH_ENV when accessed throug

2019-04-14 09:41发布

问题:

I'm working in a UNIX environment where /bin has been set up like this:

-rwxr-xr-x  1 root root 617144 Nov 19  2009 bash
lrwxrwxrwx  1 root root      4 Nov 23  2010 sh -> bash

In my environment I have set $BASH_ENV to point to my local .bashrc:

env | grep BASH
BASH_ENV=/home/users/atomicpirate/.bashrc

In addition, .bashrc has as its first line echo BASHRC READ.

I would expect /bin/sh and /bin/bash to behave exactly the same with this setup...but they don't:

/bin/bash -c 'echo $BASH_ENV'
BASHRC READ
/home/users/atomicpirate/.bashrc

/bin/sh -c 'echo $BASH_ENV'
/home/users/atomicpirate/.bashrc

In the second case, .bashrc is NOT read. Any idea why this would be the case? It seems like the symlink is breaking the expected behavior of $BASH_ENV.

回答1:

Quoting bash manpage:

If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.

Note that when run as interactive shell, modern sh uses $ENV in a manner similar to the way bash uses $BASH_ENV. This behavior is mimicked by bash as well.



回答2:

When bash is invoked as sh, it intentionally behaves differently, and disables a number of bash extensions.

One of the changes, it appears, is that it no longer reads the file dictated by $BASH_ENV. You could prove that it is nothing to do with a symlink by making the file into a regular file (temporarily) and seeing the same behaviour with a regular file.