As user aa, I need to login to an shared account bb. After I login as bb, I want to source the personal bashrc file which is only used by myself, not any other users. How could I make this happen in one line command? I find some possible answers like

sudo -iu bb bash -c 'source bashrc_aa'

but after this it will change back to user aa, I want to keep as user bb. Any solutions?

  • Why not simply su bb? This should automatically source the .bashrc – Panki Jul 18 at 10:33
  • @Panki They appear to have a separate file that they want to source (in addition to the usual shell startup files). – Kusalananda Jul 18 at 10:57
  • Can we assume that you would want to do this without modifying the .bashrc or .bash_profile files of the bb account? – Kusalananda Jul 18 at 11:00
  • take a look at --rcfile option of bash. – ctac_ Jul 18 at 15:29
  • @Kusalananda, yes and no. At first I don't want ot modify .bashrc or .bash_profile as i just want it only affect to my account aa, but as suggested by @terdon below. We can still limit the change to my account only with .bashrc modified. – ceasers Jul 19 at 8:30

As a workaround, you could simply modify bb's .profile (or ~/.bash_profile if that exists) to source the .bashrc file of whatever user is running the sudo command:

if [[ -n $SUDO_USER ]]; then
    . /home/"$SUDO_USER"/.bashrc 

Or, if you can't assume the home directory will be at /home/user_name, you could read it from /etc/passwd:

if [[ -n $SUDO_USER ]]; then
    homeDir=$(awk -F':' -v s="$SUDO_USER" '$1==s{print $6}' /etc/passwd)
    . "$homeDir"/.bashrc 

This will apply to all users who sudo into bb, but in each case it will source their bashrc. Alternatively, you could make the change for your user only:

if [[ $SUDO_USER == "aa" ]]; then
    . /home/aa/.bashrc 
  • getent passwd "$SUDO_USER" | cut -d: -f6, the ways are many. – Kusalananda Jul 18 at 11:51
  • great, it works for my issue. – ceasers Jul 19 at 8:23
  • @ceasers Good! If this solves your issue, please consider "accepting" the answer. This is the best way to show gratitude on this site. Accepting an answer not only marks the question as resolved, but also signals to future readers that the accepted answer actually solved the issue. More information about this is available here: unix.stackexchange.com/help/someone-answers – Kusalananda Jul 19 at 8:37
  • Thanks @Kusalananda for the advice. – ceasers Jul 22 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.