Search code examples
bashmacossudogit-bash

Getting error: bash: parse_git_branch: command not found


I am running the command:

sudo bash

But I keep getting an error on my terminal that says,

bash: parse_git_branch: command not found

Here is my .bash_profile file

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM$

if [ -f ~/.git-completion.bash ]; then
  . ~/.git-completion.bash
fi

export PATH=/usr/local/bin:/Applications/XAMPP/xamppfiles/bin:$PATH
export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH
export EDITOR='subl -w'



export JAVA_HOME=$(/usr/libexec/java_home)
export JAVA_HOME=$(/usr/libexec/java_home)
export JAVA_HOME=$(/usr/libexec/java_home)

Thanks in advance.


Solution

  • The problem is that parse_git_branch is defined in .bash_profile, but not exported. When you run sudo bash, it starts an nonlogin shell that sources .bashrc instead of .bash_profile. PS1 was exported and so is defined in the new shell, but parse_git_branch is not.

    Typically, you would define both PS1 and parse_git_branch in .bashrc and export neither of them. macOS is a little different from Linux, in that a terminal emulator starts a login shell instead of an ordinary interactive shell. A good practice is to put the definitions in .bashrc, then source .bashrc from .bash_profile.

    Here's how I would split up your existing .bash_profile:

    In .bashrc:

    parse_git_branch() {
        git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
    }
    
    PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
    
    [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM$
    
    if [ -f ~/.git-completion.bash ]; then
      . ~/.git-completion.bash
    fi
    

    In .bash_profile:

    # Many of the paths you were adding to PATH should already be
    # there in the default configuration; run /usr/lib/path_helper
    # to see the default.
    PATH=/Applications/XAMPP/xamppfiles/bin:/usr/local/sbin:$PATH
    export EDITOR='subl -w'
    export JAVA_HOME=$(/usr/libexec/java_home)
    
    [[ -f ~/.bashrc ]] && source ~/.bashrc