LoginSignup
159
149

Mac初心者に優しいターミナルにする(iTerm2/Oh My Zsh)

Last updated at Posted at 2022-04-24

はじめに

ターミナル(iTerm2)の便利な設定をする手順をまとめた記事です。

今回の内容は、晴れてWebエンジニアとして転職して研修を受けていた時、職場の同時期に入社したエンジニアW氏に教えてもらいました。それはもう、プログラミング学び初めの頃から欲しかった便利機能満載でした!…

独学での初学者の頃は、補完機能を付けたり、見やすくしたり、カスタマイズできることに気づくこともなく過ごして、最近までほぼデフォルトのまんまのターミナルだったので、プログラミング初学者、Mac初心者、新人プログラマの方にこの記事で共有できたらと思っています。

画面イメージ

Mac初心者に優しいターミナルのイメージとしては、こんな感じになります。

コマンドに色がつきます!
スクリーンショット 2022-04-24 14.38.05.png
lsコマンドが緑色)

エラーになる利用できないコマンドだと赤字になります!
スクリーンショット 2022-04-24 14.38.13.png

過去のコマンドが入力途中で出てきます!
スクリーンショット 2022-04-24 14.38.23.png
-laがうっすらと見える)

過去のコマンドが検索できます!
スクリーンショット 2022-04-24 14.38.36.png
Ctrl + r で下記のリストが出る。キーを押して遡らなくていい)

PC環境

  • Mac PC
  • zsh … 最近の macOS(Catalina(10.15)以降) の標準シェル
  • iTerm2 … 標準ではないターミナル

iTerm2 は macOS のターミナルの一つですが、標準のターミナルより多機能で人気のターミナルです。インストールがまだの方はぜひこの機会に使ってみてください。

※ iTerm2 のインストール方法は、公式サイトで Download クリック → zip を開く → アプリケーション に入れる → 開く

目次

手順の目次です。

1. Oh My Zsh のインストール
 1-1 .zshrc ファイルの確認(作成状況の確認)
 1-2 Oh My Zsh のインストール
 1-3 .zshrc ファイルの確認(ファイル作成されたことの確認)

2. テーマの変更
 2-1. テーマの選択
 2-2. .zshrc ファイルの編集
 2-3. テーマの反映

3. プラグインのインストール
 3-1. インストールするプラグインの確認
 3-2. プラグインを git clone → ディレクトリ移動
 3-3. .zshrc ファイルの編集
 3-4. プラグインの反映

4. peco のインストール
 4-1. インストールする peco の確認
 4-2. peco のインストール
 4-3. .zshrc ファイルの編集
 4-4. ツールの反映

(参考) .zshrc ファイル全文の確認

1. Oh My Zsh のインストール

Oh My Zsh は、ターミナルを便利にする、 zsh の設定を管理するためのツールです。

1-1. .zshrc ファイルの確認(作成状況の確認)

.zshrc ファイルは、 Zsh についての設定関連のファイルの一つです。

実行コマンド(iTerm2)
$ cat ~/.zshrc
cat: /Users/r_yamate/.zshrc: No such file or directory

上記メッセージであれば、 .zshrc ファイルは未作成の状態です。

ちなみに、 ~/ は、ホームディレクトリです。

元々 .zshrc ファイルがあって何か記述している場合は、次の 「1-2. Oh My Zsh のインストール」 をすると、その記述が上書きされてしまうため、バックアップを保存しておくなどして、上書きしないように気をつける必要があります。記述してあった内容は、インストールしたあとに、貼り付けると良いかと思います。

1-2. Oh My Zsh のインストール

Oh My Zsh の README.md のとおりにコマンド実行します。

実行コマンド
~ $ sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
実行時ログ
Cloning Oh My Zsh...
Cloning into '/Users/r_yamate/.oh-my-zsh'...
remote: Enumerating objects: 1285, done.
remote: Counting objects: 100% (1285/1285), done.
remote: Compressing objects: 100% (1244/1244), done.
remote: Total 1285 (delta 21), reused 1073 (delta 20), pack-reused 0
Receiving objects: 100% (1285/1285), 1.07 MiB | 568.00 KiB/s, done.
Resolving deltas: 100% (21/21), done.

Looking for an existing zsh config...
Using the Oh My Zsh template file and adding it to ~/.zshrc.

Time to change your default shell to zsh:
Do you want to change your default shell to zsh? [Y/n] Y
Changing the shell...
Changing shell for r_yamate.
Password for r_yamate:
Shell successfully changed to '/bin/zsh'.

         __                                     __
  ____  / /_     ____ ___  __  __   ____  _____/ /_
 / __ \/ __ \   / __ `__ \/ / / /  /_  / / ___/ __ \
/ /_/ / / / /  / / / / / / /_/ /    / /_(__  ) / / /
\____/_/ /_/  /_/ /_/ /_/\__, /    /___/____/_/ /_/
                        /____/                       ....is now installed!

Before you scream Oh My Zsh! look over the `.zshrc` file to select plugins, themes, and options.

• Follow us on Twitter: @ohmyzsh
• Join our Discord community: Discord server
• Get stickers, t-shirts, coffee mugs and more: Planet Argon Shop

iTerm2 の表示が、 矢印 と 現在のディレクトリ の シンプルなテーマ(robbyrussell) に切り替わったかと思います。
スクリーンショット 2022-04-24 13.01.45.png

1-3. .zshrc ファイルの確認(ファイル作成されたことの確認)

ls コマンドで、ファイル作成されたことの確認します。

実行コマンド
$ ls -la ~/
(以下、抜粋)
drwxr-xr-x   22 r_yamate  staff    704 12 30 23:02 .oh-my-zsh
-rw-r--r--    1 r_yamate  staff  48120 12 30 23:03 .zcompdump-mbp-5.8
-rw-------    1 r_yamate  staff     41 12 30 23:06 .zsh_history
-rw-r--r--    1 r_yamate  staff   3866 12 30 23:02 .zshrc
drwx------+ 292 r_yamate  staff   9344 12 30 23:01 Downloads

vim コマンドで、ファイルの中身を確認します。

実行コマンド
$ vim ~/.zshrc
~/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="robbyrussell"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

(以下、省略)

使用するプラグイン、テーマ、補完機能の設定などについて書いてあります。(例えば ZSH_THEME="robbyrussell はテーマの設定についての設定)

そのまま .zshrc ファイルを編集していきますので、開いておきます。

2. テーマの変更

続いて、好きなテーマに変更します。

2-1. テーマの選択

テーマの種類は GitHub で見れるので気に入ったものを使用します。(テーマの種類はデフォルトでインストールされているだけでも100種類以上ありそう…)

私は ys というテーマを選択しています。(パッと見のわかりやすさと、 Notion にコードをコピペした時のわかりやすさ、現在のディレクトリ、 Git の branch の表示がある、$が左端にあるのが良い、などの理由で選択しました)

本記事の iTerm2 画面のスクショは、 ys を使用した画面です。
スクリーンショット 2022-04-24 14.08.03.png

2-2. .zshrc ファイルの編集

Vim の インサートモードで下記の箇所を編集します。(編集できれば他のエディタでもメモ帳でもなんでも良いです)

編集: ~/.zshrc ファイル
 # Set name of the theme to load --- if set to "random", it will
 # load a random theme each time oh-my-zsh is loaded, in which case,
 # to know which specific one was loaded, run: echo $RANDOM_THEME
 # See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
- ZSH_THEME="robbyrussell"
+ ZSH_THEME="ys"

2-3. テーマの反映

ファイルを編集しただけでは、変更が反映されないので、下記コマンドを実行して、変更を反映させます。

実行コマンド
$ source ~/.zshrc

変わりましたでしょうか?

3. プラグインのインストール

続いて、プラグインをインストールします。テーマは見た目だけの変化でしたが、プラグインをインストールすると、機能の面でも便利になります。(私はW氏おすすめのプラグインを導入しただけですが、とても便利になりました!)

冒頭でご紹介した、下記のような補完機能についてのプラグインです。

スクリーンショット 2022-04-24 14.38.05.png

スクリーンショット 2022-04-24 14.38.13.png

スクリーンショット 2022-04-24 14.38.23.png

3-1. インストールするプラグインの確認

具体的には下記4つのプラグインを導入します。(リンクとGitHub説明箇所をDeepLに突っ込んだ翻訳です)

本パッケージは、シェル zsh 用のシンタックスハイライトを提供します。対話型端末の zsh プロンプトでコマンドを入力する際に、コマンドのハイライトを 可能にします。これは、コマンドを実行する前に、特に構文エラーを検出するために、 コマンドを見直すのに役立ちます。

このプロジェクトは、まだ Zsh で利用可能でない新しい補完スクリプトを収集・開発することを目的としています。これらのスクリプトは、十分に安定した時点で Zsh プロジェクトへ寄贈されるかもしれません。

履歴や完了情報をもとに、入力中にコマンドを提案してくれます。

これは、Fishシェルの履歴検索機能をクリーンルームで実現したもので、履歴から任意のコマンドの一部を入力し、↑や↓などの選択したキーを押すことで、マッチしたコマンドを循環させることができるのです。

3-2. プラグインを git clone → ディレクトリ移動

先程の4つのプラグインをそれぞれ、git clone し、 ~/.oh-my-zsh/plugins ディレクトリ以下に移動させます。

実行コマンド
$ git clone https://github.com/zsh-users/zsh-syntax-highlighting.git
$ mv zsh-syntax-highlighting ~/.oh-my-zsh/plugins
$ git clone https://github.com/zsh-users/zsh-completions.git
$ mv zsh-completions ~/.oh-my-zsh/plugins
$ git clone https://github.com/zsh-users/zsh-autosuggestions.git
$ mv zsh-autosuggestions ~/.oh-my-zsh/plugins
$ git clone https://github.com/zsh-users/zsh-history-substring-search.git
$ mv zsh-history-substring-search ~/.oh-my-zsh/plugins

3-3. .zshrc ファイルの編集

plugins の中に導入するプラグインについて追記します。

編集:~/.zshrc
plugins=(
  git
  zsh-syntax-highlighting
  zsh-completions
  zsh-autosuggestions
  zsh-history-substring-search
)

3-4. プラグインの反映

下記コマンドを実行して、変更を反映させます。

実行コマンド
$ source ~/.zshrc

色がついているか、補完されるかコマンドを入力してみてください。

4. peco のインストール

4-1. インストールする peco の確認

あと一つpecoというコマンドの検索が便利なツールを導入します。(リンクとGitHub説明箇所をDeepLに突っ込んだ翻訳です)

単純化された対話型フィルタリングツール

デモは百聞は一見にしかず! Macでプロセスを探しているところです。ご覧のように、検索結果をページ単位で確認でき、クエリを変更することも可能です。

スクリーンショット 2022-04-24 14.38.36.png

4-2. peco のインストール

peco をインストールします。

実行コマンド
brew install peco

macOS 用パッケージマネージャーの Homebrew のインストールがまだで brew コマンドが使えない場合は、下記コマンドでインストールします。

※実行コマンド
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

4-3. .zshrc ファイルの編集

下記を任意の箇所に追記します。(私は一番下の行に追記しました)

編集:~/.zshrc
# peco
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

4-4. ツールの反映

これまで同様、下記コマンドを実行して、変更を反映させます。

実行コマンド
$ source ~/.zshrc

ctrl + r を入力すると、過去のコマンドが出てきます。

(選択しない場合、ESCキーで戻れます)

手順としては以上となります!

(参考) .zshrc ファイル全文の確認

これまで記述内容は以下の通りです。

~/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="ys"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# 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 one of the following lines to change the auto-update behavior
# zstyle ':omz:update' mode disabled  # disable automatic updates
# zstyle ':omz:update' mode auto      # update automatically without asking
# zstyle ':omz:update' mode reminder  # just remind me to update when it's time

# Uncomment the following line to change how often to auto-update (in days).
# zstyle ':omz:update' frequency 13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# 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.
# You can also set it to another string to have that shown instead of the default red dots.
# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
# 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.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# 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?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(
  git
  zsh-syntax-highlighting
  zsh-completions
  zsh-autosuggestions
  zsh-history-substring-search
)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# 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"

# 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"

# peco
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

おわりに

今回、コマンドうろ覚えの初心者の頃にこそ知りたかった機能の導入を記事にしてみました。

今後も便利にアップデートしていきたいので、オススメのプラグインなどありましたら教えていただけますと幸いです。

ありがとうございました。

その他参考

記事内のスクショのとおり、私は iTerm2 を 透過させてフルスクリーンで表示 させて使用しているのですが、こちらの記事を参考に設定しました。
HotKeyを設定してiTerm2をショートカットで開ける ようにするのも便利だと思います。

159
149
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
159
149