LoginSignup
11
10

More than 5 years have passed since last update.

man見まくっているヘタレ行為をzshのコマンド履歴に入れない方法

Posted at

zshで「manの実行をコマンド履歴に入れない」ことを紹介します。

結論

.zshrc
setopt hist_ignore_space

alias man=' man'

autoload -Uz run-help
autoload -Uz run-help-git
# ... 中略 ...
alias run-help=' run-help'

hist_ignore_space

zsh には hist_ignore_space というオプションがあって、これを設定すると先頭に半角スペースを入れたコマンドは履歴に入らない。実行に注意が必要なものや、その場限りでしか使わないようなコマンドのときに便利であろう。

% setopt hist_ignore_space
% ls        ←履歴に入る
%  rm -rf * ←履歴に入らない

man(1) をコマンド履歴に入れない方法

% man git

筆者としては「man見まくっているヘタレ行為をzshのコマンド履歴に入れたくない・後で自分が見たくもない」というしょうもない理由がある。よって、上のようにあわてて入力したとしても履歴に残らないで欲しいのである。

zsh の man で hist_ignore_space の説明を見ると下記のようなことが書いてある。

HIST_IGNORE_SPACE (-g)
Remove command lines from the history list when the first character on the line is a space, or when one of the expanded aliases contains a leading space. Only normal aliases (not global or suffix aliases) have this behaviour. Note that the command lingers in the internal history until the next command is entered before it vanishes, allowing you to briefly reuse or edit the line. If you want to make it vanish right away without entering another command, type a space and press return.

上で強調しておいた箇所のとおり、エイリアスを展開した結果で半角スペースから始まっているときも、履歴に入れない挙動となる。

% setopt hist_ignore_space
% alias a=echo
% a foobar  ←履歴に入る
% alias a=' echo'
% a foobar  ←履歴に入らない
% alias b=a
% b foobar  ←履歴に入らない

よって、目的を達成するには下記のようにエイリアスを .zshrc などに設定すれば良い。

.zshrc
setopt hist_ignore_space

alias man=' man'

もちろん、man(1) に関わらず任意のコマンド・関数に対してこの方法は使える。

^[h の実行をコマンド履歴に入れない方法

zsh では ^[h (すなわちM-h) を押して man を見ることの方が遥かに便利である。(詳細はzsh で Git の man を素早く見るを参照のこと)

この場合は man ではなく run-help が実行されるので注意が必要なことがある。run-helpman のエイリアスとしている場合、man を既述のとおりの半角スペース始まりのエイリアスになってれば履歴に追加されない。run-help が関数定義の場合、明示的に run-help を半角スペース始まりのエイリアスを定義する必要がある。

特に autoload run-help をする場合で、履歴に追加されないようにするためには、alias run-help=' run-help' が必須だ:

.zshrc
setopt hist_ignore_space

autoload -Uz run-help
autoload -Uz run-help-git
# ... 他の run-help-* はお好みで ...
alias run-help=' run-help'
11
10
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
11
10