Linux (RedHat) `sudo su -l <<user_acct>>` does not source profile

6,258

Solution 1

When it's a login shell, bash first looks for ~/.bash_profile. If it doesn't find it, it looks for ~/.bash_login. If it doesn't find it, it looks for ~/.profile. In any case, even if the login shell is interactive, bash doesn't read ~/.bashrc.

I recommend to stick to the following content in ~/.bash_profile, and to not have a ~/.bash_login:

if [ -e ~/.profile ]; then . ~/.profile; fi
case $- in *i*) if [ -e ~/.bashrc ]; then . ~/.bashrc; fi;; esac

That way your .profile is loaded whether your login shell is bash or some other sh variant, and your .bashrc is loaded by bash whether the shell is a login shell or not.

Solution 2

Don't do sudo su, that's not needed. sudo -i -u loginname is what you want.

Share:
6,258
user1766760
Author by

user1766760

Updated on September 18, 2022

Comments

  • user1766760
    user1766760 almost 2 years

    As stated, having trouble with loading the default profile of <<user_acct>> when doing sudo su -l <<user_acct>>.

    Inside .profile,

    if [ -r "${HOME}/.profile.custom" ]; then
        . "${HOME}/.profile.custom"
    fi
    

    From what I've read (for example, answers similar to this one), -l should have triggered a login shell and therefore sourced .profile, but it doesn't seem to be working because the environment variables set in .profile.custom is not there (vs. if I just ran . .profile, they show up.

    Revised question: Any thoughts why or how to get around this issue?

    • depquid
      depquid about 11 years
      Are you using Bash? What directory is .profile in? Why ~/.profile.custom instead of just putting the "custom commands" in ~/.profile (that's what it's there for)?
    • user1766760
      user1766760 about 11 years
      @depquid Yes on Bash... actually I found out that I should be using .bash_profile instead to set the additional env variables. .profile is under the home directory of the <<user_acct>>. As for .profile.custom... no particular reason I guess, just that these are custom things so we put it in a custom file (just our team's preference)
  • user1766760
    user1766760 about 11 years
    This looks really promising, but unfortunately I am not allowed to run this command on my team. Or rather, our admin didn't want to open up the ability to run bash under the <<user_acct>>... Not really seeing why we shouldn't open up the permission if we already have sudo su but out of my control shrug
  • depquid
    depquid about 11 years
    Yeah, you are running Bash as "<<user_acct>>"; that's why it's called .bash_profile.
  • user1766760
    user1766760 about 11 years
    I can definitely see a benefit to setting up an OS-agnostic profile. I'm going to mark your answer as accepted since there are learning points that I think could benefit others. Cheers!