Function defined in my user's .bashrc causes an error when I sudo su

I have a function defined in my user's .bashrc file that displays my current git branch name at my command prompt:

parse_git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
PS1="\\[$(tput setaf 7)\\]\\w \$(parse_git_branch)> \\[$(tput sgr0)\\]"

When I sudo to su, it looks like my PS1 is carried over, and after every command I get the error bash: parse_git_branch: command not found.

What can I change so that when I sudo to another user, its PS1 is used and not that of my user?

Edit: It seems like this only happens after I use source a Python virtualenv. If I sudo su before I source the virtualenv, this error does not occur.

5

2 Answers

Did you ever expor PS1 somewhere (e.g. in your Python virtualenv)? I always have this line in my .bashrc or .bash_profile:

export -n PS1 # unexport PS1 so sub-processes will not inherit it

So try export -n PS1 before you sudo.

PS1 is not being reset by sudo, it's kept by default. Functions are part of the bash environment, but are not preserved by sudo. You can do any of several things:

  • instead use sudo su - so you get a login shell, that will reset PS1
  • set env_reset to "clean up" the environment, possibly with env_keep
  • set SUDO_PS1 and sudo will place that value in PS1
  • use sudo -i which is similar to su - (you'll need to add your shell to the sudoers file)
  • check the variable SUDO_COMMAND in your .bashrc and reset PS1

The list of variables that sudo keeps (may vary by version, check env.c in the source) includes:

DISPLAY COLORS LS_COLORS HOSTNAME PS1 PS2 TZ

This is a hardcoded list, it's not the same thing as env_keep (i.e. "env_keep -=" won't change it).

Run sudo -V as root for a full list of variables preserved or removed (for sudo version >= v1.7).

One final suggestion, you could make your PS1 more robust by checking if the function exists:

PS1="\\[$(tput setaf 7)\\]\\w \$(type -t parse_git_branch >/dev/null && parse_git_branch)> \\[$(tput sgr0)\\]"
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like