LoginSignup
6

More than 3 years have passed since last update.

【macOS】プロンプトにgitのブランチ名を出す方法

Last updated at Posted at 2019-09-25

概要

  • git-prompt.shでターミナル上でgitのブランチ名がわかるようにする
  • 環境変数PS1をカスタマイズしてプロンプトに時刻を出す
  • git-completion.bashでgitコマンドがtab補完されるようにする

実現方法

1. Homebrewでgitをインストール

$ brew install git
$ git --version
git version 2.18.0

Homebrewでgitをインストールするとgit-prompt.shgit-completion.bashもインストールされる。

2. 実行権限を与える

$ chmod a+x /usr/local/etc/bash_completion.d/git-prompt.sh
$ chmod a+x /usr/local/etc/bash_completion.d/git-completion.bash

3. .bashrcにPS1の設定を追記する

.bashrc
# read script
source /usr/local/etc/bash_completion.d/git-prompt.sh
source /usr/local/etc/bash_completion.d/git-completion.bash
# option
GIT_PS1_SHOWDIRTYSTATE=true
# git ps1
export PS1='\[\033[37m\][\t \[\033[36m\]\u\[\033[37m\]@\h \[\033[32m\]\W\[\033[37m\]]\[\033[31m\]$(__git_ps1)\[\033[00m\]\$ '

設定可能なオプション

設定したいオプションをtrueにする

  • GIT_PS1_SHOWDIRTYSTATE
    • addしてない変更がある(unstaged)ときに*を表示
    • add済みでcommitしてない変更がある(staged)ときに+を表示
  • GIT_PS1_SHOWUNTRACKEDFILES
    • addしてない新規ファイルがある(untracked)ときに%を表示
  • GIT_PS1_SHOWSTASHSTATE
    • stashがある(stashed)ときに$を表示
  • GIT_PS1_SHOWUPSTREAM
    • 現在のブランチがupstreamより進んでいるときは>を表示
    • 現在のブランチがupstreamより遅れているときは<を表示
    • 現在のブランチがupstreamより遅れてるけど自分の変更もあるときは<>を表示

PS1に使える設定

私が使ってる設定について紹介。
他にも色々と使えるのでこちらを参考にどうぞ:Bashのプロンプト変更

エスケープ文字

  • \h:ホスト名
  • \t:時刻(HH:MM:SS、24時間表記)
  • \u:ユーザー名
  • \W:現在のディレクトリ名

文字の色

  • \[\033[37m\]:White
  • \[\033[36m\]:Light Cyan
  • \[\033[32m\]:Light Green
  • \[\033[31m\]:Light Red

4. 変更を反映する

もし.bashrcを読み込んでない場合は.bash_profileに下記を追記する。

.bash_profile
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

設定を反映する。

$ source .bashrc
$ source .bash_profile

はい完成

こんな感じで出力されるようになります。

[14:50:54 user@host current_dir] (branch)$

参考:「Git補完をしらない」「git statusを1日100回は使う」そんなあなたに朗報【git-completionとgit-prompt】

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
6