User environment is not sourced with chroot

Labynocle picture Labynocle · Nov 26, 2012 · Viewed 8k times · Source

I have a little problem with a chroot environment and I hope you could help me :)

Here's my story:

1 - I created a user demo (with a home like /home/demo) and I chrooted him thanks to a script /bin/chrootshell which is as following:

#!/bin/bash
exec -c /usr/sbin/chroot /home/$USER /bin/bash --login -i

2 - Usual login authentication are disabled for this user, so I have to use su - demo to be logged as him

Everything works well (like all the chrooted system commands or my java configuration). But each time I become user demo, it seems my .bashrc or /etc/profile are not sourced... And I don't know why.

But if I launch a manual bash it works as you can see here:

root@test:~# su - demo
bash-4.1$ env
PWD=/
SHELL=/bin/chrootshell
SHLVL=1
_=/bin/env
bash-4.1$ bash
bash-4.1$ env
PWD=/
SHLVL=2
SHELL=/bin/chrootshell
PLOP=export variable test
_=/bin/env

As you can see, my $PLOP variable (describes in /.bashrc == /home/demo/.bashrc) is well set in the second bash, but I don't know why

Thanks in advance if you have any clue about my issue :)

edit: What I actually don't understand is why SHELL=/bin/chrootshell ? in my chroot env I declare my demo user with /bin/bash shell

Answer

lesmana picture lesmana · Nov 27, 2012

As far as I can tell the behaviour that you are experiencing is bash working as designed.

In short: when bash is started as a login shell (that is what happens when you call bash with --login) it will read .profile but not .bashrc. When bash is started as a non login shell then bash will read .bashrc but not .profile.

Read the bash manual chapter about startup files for more information.

My suggestion to work around this design decision is to create a .bash_profile with the following content:

if [ -f "~/.profile" ]; then
    source "~/.profile"
fi

if [ -f "~/.bashrc" ]; then
    source "~/.bashrc"
fi

That will make bash read .profile and .bashrc if started as login shell, and read only .bashrc if started as non login shell. Now you can put the stuff which needs to be done once (during login) in .profile, and the stuff which needs to be done everytime in .bashrc.