Macのシェルをbashからzshに変える方法と設定(oh-my-zshとpecoも追加)
私生活でも仕事でもほそぼそとプログラムを書いてるけど前々からシェルをデフォルトのbashからzshに変えたいと思っていた。
どうせならシェルだけではなくターミナル周り全般やCUI環境をしっかり作り直したいと思ってはいたけどなかなか敷居が高く今までやろうと決心がつかなかった。
なによりこういう情報を探してて思うのは初心者がzshを理解してステップアップしていく過程をどう過ごすか記載されている情報が少ないこと!
とりあえず俺の設定ファイル使いなよみたいな記事が多く、githubからcloneしてくれば確かに使えるんだけど、ブラックボックスなまま使うのがすごい嫌だなと常々感じていた。
なので自分の勉強も兼ねて少しずつzshを理解して使いこなせるようになる過程を書いていきたいと思います! (これはvimやtmuxなども同様に記録していきたい。)
ちなみに私の環境はMacOSX 10.10.5です。
という手順で紹介します
zshについて
シェルにも色いろあるのdすがBourne Shell系をベースとして、ksh、csh(tcsh)、bashの各シェルの機能を取り込み,作られたのがzsh(ゼットシェル)です。zは最後の、究極のという意味でzなんですね。
主なメリットとしては
- 優れた入力補完
- 非標準コマンド(brew、gitとか)の入力補完
- 見やすいカラーリング
- bashより処理が高速
- ターミナル間でのhistory共有
- gitのカレントブランチの表示
- コマンドの入力ミスを修正してくれる
- 処理後の通知
などがあげられます。
zshのインストール
ではではそんな便利なzshをインストールしてみましょう。 macではデフォルトでzshが入ってますがバージョンが古いためhomebrewでインストールしましょう。
brewについてはこちらを参照
brew install --without-etcdir zsh
ついでにzshの補完機能をパワーアップする「zsh-completions」もインストール。こいつのおかげでgitなどの非標準コマンドも補完されます!(設定ファイルへの追記は後で)
brew install zsh-completions
ここでHomebrewで入れたzshへのパスを追加します。
vi /etc/shells
開いたファイルの最後に/usr/local/bin/zshを追加
# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.
/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
/usr/local/bin/zsh #ここに追加
ではログインシェルをzshに切り替えましょう!
chsh -s /usr/local/bin/zsh
パスワードを聞かれます。無事終わってからターミナルを再起動してみるとzshに切り替わってるはずです! これでbashともおさらば。
oh-my-zshのインストールと.zshrcの設定
zshのインストールと設定が一段落したのでoh-my-zshをインストールします。 oh-my-zshはzshを管理するフレームワークで
- 豊富なプロンプトテーマ
- 便利なaliasの設定
- プラグインの利用
といったメリットが有ります。
以下のコマンドでoh-my-zshをインストールしましょう。
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
oh-my-zshをインストールすると~/.zshrcというファイルが作成されます。これがzshの設定ファイルです。
vi ~/.zshrc
oh-my-zshをインストールした時点で色々とファイルには書かれてますが
https://gist.github.com/mollifier/4979906
これを参考にさらに設定を追記しました。
# Path to your oh-my-zsh installation. export ZSH=/Users/yuta144k/.oh-my-zsh # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. # oh-my-zshで利用できるテーマを指定 ZSH_THEME="robbyrussell" # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to use hyphen-insensitive completion. Case # sensitive completion must be off. _ and - will be interchangeable. # HYPHEN_INSENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. # DISABLE_AUTO_UPDATE="true" # Uncomment the following line to change how often to auto-update (in days). # export UPDATE_ZSH_DAYS=13 # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. # ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. # COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # HIST_STAMPS="mm/dd/yyyy" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. # oh my zshで利用できるプラグインを指定 plugins=(brew brew-cask ruby osx bundler rails) # User configuration export PATH="/usr/local/sbin:$PATH" # export MANPATH="/usr/local/man:$MANPATH" source $ZSH/oh-my-zsh.sh # You may need to manually set your language environment # export LANG=en_US.UTF-8 # Preferred editor for local and remote sessions # if [[ -n $SSH_CONNECTION ]]; then # export EDITOR='vim' # else # export EDITOR='mvim' # fi # Compilation flags # export ARCHFLAGS="-arch x86_64" # ssh # export SSH_KEY_PATH="~/.ssh/dsa_id" # Set personal aliases, overriding those provided by oh-my-zsh libs, # plugins, and themes. Aliases can be placed here, though oh-my-zsh # users are encouraged to define aliases within the ZSH_CUSTOM folder. # For a full list of active aliases, run `alias`. # # Example aliases # alias zshconfig="mate ~/.zshrc" # alias ohmyzsh="mate ~/.oh-my-zsh" # 少し凝った zshrc # License : MIT # http://mollifier.mit-license.org/ ######################################## # 環境変数 export LANG=ja_JP.UTF-8 # 色を使用出来るようにする autoload -Uz colors colors # vim風キーバインドにする bindkey -v # ヒストリの設定 HISTFILE=~/.zsh_history HISTSIZE=1000000 SAVEHIST=1000000 # 単語の区切り文字を指定する autoload -Uz select-word-style select-word-style default # ここで指定した文字は単語区切りとみなされる # / も区切りと扱うので、^W でディレクトリ1つ分を削除できる zstyle ':zle:*' word-chars " /=;@:{},|" zstyle ':zle:*' word-style unspecified ######################################## # for zsh-completions fpath=(/usr/local/share/zsh-completions $fpath) # 補完 # 補完機能を有効にする autoload -Uz compinit compinit -u # 補完で小文字でも大文字にマッチさせる zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' # ../ の後は今いるディレクトリを補完しない zstyle ':completion:*' ignore-parents parent pwd .. # sudo の後ろでコマンド名を補完する zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin \ /usr/sbin /usr/bin /sbin /bin /usr/X11R6/bin # ps コマンドのプロセス名補完 zstyle ':completion:*:processes' command 'ps x -o pid,s,args' ######################################## # vcs_info autoload -Uz vcs_info autoload -Uz add-zsh-hook zstyle ':vcs_info:*' formats '%F{green}(%s)-[%b]%f' zstyle ':vcs_info:*' actionformats '%F{red}(%s)-[%b|%a]%f' function _update_vcs_info_msg() { LANG=en_US.UTF-8 vcs_info RPROMPT="${vcs_info_msg_0_}" } add-zsh-hook precmd _update_vcs_info_msg ######################################## # オプション # 日本語ファイル名を表示可能にする setopt print_eight_bit # beep を無効にする setopt no_beep # フローコントロールを無効にする setopt no_flow_control # Ctrl+Dでzshを終了しない setopt ignore_eof # '#' 以降をコメントとして扱う setopt interactive_comments # ディレクトリ名だけでcdする setopt auto_cd # cd したら自動的にpushdする setopt auto_pushd # 重複したディレクトリを追加しない setopt pushd_ignore_dups # 同時に起動したzshの間でヒストリを共有する setopt share_history # 同じコマンドをヒストリに残さない setopt hist_ignore_all_dups # スペースから始まるコマンド行はヒストリに残さない setopt hist_ignore_space # ヒストリに保存するときに余分なスペースを削除する setopt hist_reduce_blanks # 高機能なワイルドカード展開を使用する setopt extended_glob # ウインドウ名の表示 set -g set-titles on set -g set-titles-string '#W' ######################################## # キーバインド # ^R で履歴検索をするときに * でワイルドカードを使用出来るようにする bindkey '^R' history-incremental-pattern-search-backward ######################################## # エイリアス alias la='ls -a' alias ll='ls -l' alias rm='rm -i' alias cp='cp -i' alias mv='mv -i' alias mkdir='mkdir -p' # sudo の後のコマンドでエイリアスを有効にする alias sudo='sudo ' # グローバルエイリアス alias -g L='| less' alias -g G='| grep' # C で標準出力をクリップボードにコピーする # mollifier delta blog : http://mollifier.hatenablog.com/entry/20100317/p1 if which pbcopy >/dev/null 2>&1 ; then # Mac alias -g C='| pbcopy' elif which xsel >/dev/null 2>&1 ; then # Linux alias -g C='| xsel --input --clipboard' elif which putclip >/dev/null 2>&1 ; then # Cygwin alias -g C='| putclip' fi ######################################## # OS 別の設定 case ${OSTYPE} in darwin*) #Mac用の設定 export CLICOLOR=1 alias ls='ls -G -F' ;; linux*) #Linux用の設定 alias ls='ls -F --color=auto' ;; esac # vim:set ft=zsh: #ここに.bashrcや.bash_profileに書かれている$PATHの設定を転記しましょう export PATH=/usr/local/bin:$PATH export PATH=$(brew --prefix)/bin:$PATH # rbenv & phpenv export PATH=$HOME/.rbenv/bin:$PATH eval "$(rbenv init - zsh)" export PATH=$HOME/.phpenv/bin:$PATH eval "$(phpenv init - zsh)"
ZSH_THEMEというところのテーマ名を変えるとシェルのカラーリングや見た目が変わります。お好みで変えてみましょう!
テーマはこちらのサイトで見れます
https://github.com/robbyrussell/oh-my-zsh/wiki/Themes
お好きなテーマ名を設定ファイルに書いてターミナルを再起動してみてください。
その他コメント参考にお好みで修正していきましょう。よくわからない場合はコメントアウトしてみて挙動の変化をみてみてもいいかもしれません。 最後の.bashrcからの$PATHの転記はやっておいてくださいね! rbenvの eval "$(rbenv init - zsh)" はzshを追加しないとうまくいかない場合があるようです。
設定を終えたら
source ~/.zshrc
で設定ファイルを再読み込みしてください。
これでzsh環境が構築できました!
pecoのインストールと設定
では最後にpecoを導入しましょう。
brew install peco
pecoはコマンド出力結果のインクリメントサーチが出来るツールです。bashでC+rでヒストリー履歴の検索ができたかと思いますがそれを超絶便利にするものがこれです!
.zshrcにpecoの設定を追記してzshのヒストリと連携させましょう! zshのCtrl+rをオーバーライドする形で設定します!
vi ~/.zshrc
function peco-select-history() { local tac if which tac > /dev/null; then tac="tac" else tac="tail -r" fi BUFFER=$(\history -n 1 | \ eval $tac | \ peco --query "$LBUFFER") CURSOR=$#BUFFER zle clear-screen } zle -N peco-select-history bindkey '^r' peco-select-history
これを.zshrcに追記してください。
source .zshrc
このコマンドでzshrcを再読込して設定を反映します。
さらにキーバインドの設定を追加します。
mkdir ~/.peco
vi ~/.peco/config.json
{ "Keymap": { "M-v": "peco.SelectPreviousPage", "C-v": "peco.SelectNextPage", "C-c": "peco.Cancel" } }
~/.peco/config.jsonを以上のように書き足して保存。
これで設定が完了しました!
ではzsh上でC+rを実行してみましょう!
ただのヒストリ検索ではなくpecoが起動していれば成功です!
以上でシェルをzshにしてoh-my-zshを入れて少し設定を加えて、pecoを入れてヒストリ検索を超絶便利にするところまでできました!
まだまだzshはチューニングできる部分があると思うので勉強しながら少しずつ紹介したいと思います!