Adding git branch on the Bash command prompt

前端 未结 13 2070
感情败类
感情败类 2020-11-30 16:15

I tried adding the git branch I\'m currently working on (checked-out) on the bash prompt without success.. (while keeping my current path which shows the active dir

13条回答
  •  温柔的废话
    2020-11-30 17:14

    At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.

    For example, I open it using the VS Code using this command: code .bash_profile.

    Then just paste the following codes to your Bash.

    parse_git_branch() {
         git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
    }
    
    export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
    

    The function

    parse_git_branch()

    will fetch the branch name & then through PS1 you can show it in your terminal.

    Here,

    \u = Username

    @ = Static Text

    \h = Computer Name

    \w = Current Directory

    $ = Static Text

    You can change or remove these variables for more customization.


    If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.

    If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.


提交回复
热议问题