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.
52 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 itSo 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 resetPS1 - set
env_resetto "clean up" the environment, possibly withenv_keep - set
SUDO_PS1and sudo will place that value inPS1 - use
sudo -iwhich is similar tosu -(you'll need to add your shell to thesudoersfile) - check the variable
SUDO_COMMANDin your.bashrcand resetPS1
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 TZThis 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