LoginSignup
57
47

More than 5 years have passed since last update.

BashのプロンプトにGitのブランチ名を含める。

Posted at

はじめに

目下、以下の書籍

独習Git (翔泳社 2016/2/26初版)

を使ってGitを学習しておりまして、この本の第9章「9.6 さらなる探求」で、
首題のようにシェルプロンプトにブランチ名を含めようというトピックが
載っていたので実際にやってみました。その手順を以下に記載しました。

インストール対象マシン

  • Mac mini (Late2012)
  • OS X El Captitan バージョン 10.11.3

現状確認

ターミナルを起動。現状のプロンプトは、以下のようにカレントディレクトリのみ

~ $ date
2016年 3月30日 水曜日 12時19分02秒 JST
~ $ cat ~/.bash_profile | grep PS1
export PS1='\W $ '
~ $ cd gitwork
gitwork $ pwd
/Users/ykt68/gitwork
gitwork $

git-prompt.shの入手

以下のgit-prompt.shを自分のホームディレクトリにダウンロード

ダウンロードしてきたgit-prompt.shの冒頭に、使い方が書いてあるのでざっと読む。(英文)

隠しファイルにリネームする。

~ $ mv git-prompt.sh .git-prompt.sh
~ $ ls -la .git-prompt.sh
-rw-r--r--@ 1 ykt68 staff 16102 3 30 12:37 .git-prompt.sh

※今後も git-prompt.shは改良されるかもしれないので、ファイルサイズは変わる
かもしれません。

.bashrc に追記

.git-prompt.shの冒頭のコメント

2) Add the following line to your .bashrc/.zshrc:
    source ~/.git-prompt.sh

のとおりに .bashrc をviなどで開き、最後に

source ~/.git-prompt.sh

を追加して保存

.bash_profile の PS1を修正

.git-prompt.shの冒頭のコメント

3a) Change your PS1 to call __git_ps1 as
   command-substitution:
   Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

のとおりに、.bash_profile で指定しているPS1の設定を修正する。

修正前:

export PS1='\W $ '

修正後:

export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

上記のように修正して保存

動作確認

上記のように、.bashrcと.bash_profileを修正して保存後、あらためてターミナル
を起動し、以下のように修正が反映されていることを確認した。

[ykt68@MacMini ~]$ cd gitwork
[ykt68@MacMini gitwork]$ cd math
[ykt68@MacMini math (another_fix_branch)]$ git branch
* another_fix_branch
master
new_feature
[ykt68@MacMini math (another_fix_branch)]$ git checkout master
Switched to branch 'master'
[ykt68@MacMini math (master)]$ git checkout new_feature
Switched to branch 'new_feature'
[ykt68@MacMini math (new_feature)]$

なお、上記のディレクトリ mathおよび各ブランチは、独習Git (翔泳社 2016/2/26初版)
にそって実習したときに作成したもの。

以上

57
47
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
57
47