macでbashからzshへ乗り換えた話

今までずっとbashを使ってきましたが、補完が強力とか作業がいろいろ捗るとか聞くので、重い腰を持ち上げてzshに乗り換えることを決めました。

環境

  • MacOS Sierra 10.12.3
  • Homebrew 0.9.9

zshインストール

Homebrewは入れている前提です。

以下のコマンドでzshをインストールします。zsh-completionsは、zshの補完機能を強化するプラグインです。

$ brew install zsh
$ brew install zsh-completions

ログインシェルの変更

/etc/shellにログインシェルにできるプログラムがフルパスで記述されています。インストールしたzshのパスを追記します。

$ sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells"

シェルを変更します。パスワードを入力後、ターミナルを再起動します。

$ chsh -s /usr/local/bin/zsh

初期設定

再起動後、以下のようなメッセージが表示されます。

This is the Z Shell configuration function for new users,
zsh-newuser-install.
You are seeing this message because you have no zsh startup files
(the files .zshenv, .zprofile, .zshrc, .zlogin in the directory
~).  This function can help you with a few settings that should
make your use of the shell easier.

You can:

(q)  Quit and do nothing.  The function will be run again next time.

(0)  Exit, creating the file ~/.zshrc containing just a comment.
     That will prevent this function being run again.

(1)  Continue to the main menu.

--- Type one of the keys in parentheses ---
  • (q): 何もしません。次回ターミナル起動時に同じメッセージが再度表示されます。
  • (0): ホームディレクトリ以下に.zshrcが作成されます。ここに設定を自分で書き込む方式です。
  • (1): 対話式メニューで.zshrcの設定を決定していく方式です。

0を選択します。

zplugのインストール

zshプラグインマネージャであるzplugをインストールします。

zshプラグインマネージャといえばoh-my-zshやantigenも有名みたいですが、 参考にもあるようにパフォーマンス等の面でzplugが最近は流行っているよう。

$ brew install zplug

zplugのREADMEに従って~/.zshrcに設定を追加します。

# brewのインストールパスを設定する
export ZPLUG_HOME=/usr/local/opt/zplug
source $ZPLUG_HOME/init.zsh
# pluginの追加
## zsh-completions
zplug "zsh-users/zsh-completions"¬
fpath=(/usr/local/opt/zplug/repos/zsh-users/zsh-completions $fpath)¬
## git
zplug "plugins/git", from:oh-my-zsh
## 未インストール項目をインストールする
if ! zplug check --verbose; then
  printf "Install? [y/N]: "
  if read -q; then
       echo; zplug install
  fi
fi
## コマンドをリンクして、PATH に追加し、プラグインは読み込む
zplug load --verbose

上記で追加しているのは、git-completionsとoh-my-zshのgitプラグインです。

git-completionsは、vagrantコマンドやrailsコマンドなど、zshの補完を強化するプラグインです。 上記のみで補完が有効にならない場合は以下のコマンドも実行します。

$ rm -f ~/.zcompdump; compinit

oh-my-zshのgitプラグインは大量のgitのaliasや関数を読み込みます。(例:git status -s > gss) 全部はなかなか覚えられませんが、仕様頻度の高いaliasを使うだけでも意外と快適です。

vcs_infoの設定

vcsとはVersion Control Systemsの略です。 Gitとかバージョン管理システムの情報をターミナルに表示することが可能になります。

今回はシンプルにgitレポジトリ内ではブランチ名を表示するようにします。

# vcs_info
autoload -Uz vcs_info
## branchの表示
zstyle ':vcs_info:*' formats '(%b)'
precmd() { vcs_info }

#prompt
PROMPT='%n@%m: %~ ${vcs_info_msg_0}'

その他設定

上記に加えて、lessやgrepのグローバルエイリアス、historyの端末間での共有など 基本的な設定を追加したものが以下になります。

uu64/.zshrc

参考