LoginSignup
2
2

More than 3 years have passed since last update.

git のブランチ名を bash のコマンドプロンプトに表示する

Last updated at Posted at 2020-10-11

git のブランチ名を bash のコマンドプロンプトに表示する

git のブランチ名を bash のコマンドプロンプトに表示する方法です。(Ubuntu 20.04.1 で確認しました)

設定方法

if [ -e /etc/bash_completion.d/git-prompt ]; then
    source /etc/bash_completion.d/git-prompt
    PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] $(__git_ps1 " (%s)") \$ '
fi
  • /etc/bash_completion.d/git-promptsudo apt install -y git で git をインストールすると作成されます。
  • Ubuntu ではデフォルトで以下のように定義されているので、最後に $(__git_ps1 " (%s)") \$ を追加します。

変更前:
PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$'

変更後:
PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] $(__git_ps1 " (%s)") \$

コメント

/etc/bash_completion.d/git-prompt の中身を確認すると以下のようになっています。

if [[ -e /usr/lib/git-core/git-sh-prompt ]]; then
    . /usr/lib/git-core/git-sh-prompt
fi

/usr/lib/git-core/git-sh-prompt の先頭にコメントがあります。
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh でも参照できます。
(GPL のようです)

#    3a) Change your PS1 to call __git_ps1 as
#        command-substitution:
#        Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
#        ZSH:  setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
#        the optional argument will be used as format string.

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2