A lot of my workflow involves using a sudo interactive session (sudo -i) as a service user that is able to run certain things that my personal username can't. When I do this, I like to preserve my PS1 variable and some other little bash niceties. As I can't modify the service user's .bashrc, I have a script set up in my home directory to export this as I like it. For example, my workflow might look like:

ssh me@remote
sudo -i -u service_user
. /home/me/ps1.sh
*service user commands here*

I'd like to roll the sudo command and sourcing the PS1 script into one command. My thought was to use something like sudo -i -u service_user -c sh ". /home/me/ps1.sh", which will pass the command in - the problem is that the session will immediately exit after the command runs, rather than hanging in interactive mode. Short of requesting the admin allow the PS1 variable to be preserved through sudo, is there anything I can do?

1 Answer 1


You could use --rcfile to tell bash to read your ps1.sh file instead of the service_user's .bashrc:

sudo -i -u service_user bash --rcfile /home/me/ps1.sh

The execution flow then will be something like sudo running bash -lc 'bash --rcfile /home/me/ps1.sh' as service_user. If you want to source the service_user's .bashrc, you can do so in the ps1.sh file.

The -i in sudo -i is not "interactive", it's a login shell (i.e., a shell is started which will process the target user's .profile or equivalent and run the given command). That's why the execution has a bash -l wrapping the actual command. If the service_user's .profile is irrelevant, you can just do:

sudo -u service_user bash --rcfile /home/me/ps1.sh
  • Thank you for the solution and explanation!
    – matt
    Commented Dec 12, 2019 at 2:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .