Bash – Why root does not source .bash_profile

bashrcosxrootsu

Every time I try to login as root using su (not su -), it doesn't source .bash_profile in user1's home directory.

Basically, my /var/root directory doesn't have .bash_profile, so I put a copy of .bash_profile in /var/root to test su -.

It doesn't automatically source .bash_profile (in var/root), either.

Anyway, I want to make .bash_profile, of user1, sourced in root account automatically when I use su.

What should I do?

(It worked before! One day, it just doesn't source! Maybe something changed settings in bash? It works when I enter source .bash_profile after login.)

I am using Mac and OS X Yosemite.

Best Answer

The default shell for root on OS X is /bin/sh. Its sh is also a version of bash, but when invoked with the name sh Bash:

tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.

When invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. ... a shell invoked as sh does not attempt to read and execute commands from any other startup files

That is, it doesn't read .bash_profile at all, regardless of whether it was invoked as a login shell or not. You can use .profile instead, or even symlink one to the other. If you launch a login shell with su -l, .profile is loaded on startup, but .bash_profile will never be.


You can also use dscl to change root's shell (noting that /etc/passwd is not used to determine the shell on OS X). You can check root's current shell with dscl . -read /Users/root UserShell; consult the documentation and think carefully before changing it to something else.

Another approach is simply to change your su invocation to force executing bash immediately.

Given what you've said, I'd probably recommend the symlink, but you may wish to look into the changes that Bash's POSIX mode makes and decide whether you want to have them or not.

Related Question