Zshインタラクティブモードでコメントアウトを使用する

環境構築
zsh
shell
Author

Ryo Nakagami

Published

2025-10-10

Modified

2025-10-10

INTERACTIVE_COMMENTS option

Definition 1 INTERACTIVE_COMMENTS

Zsh sourceforge > 6.7 Commentsに以下のように定義されています

In non-interactive shells, or in interactive shells with the INTERACTIVE_COMMENTS option set, a word beginning with the third character of the histchars parameter (‘#’ by default) causes that word and all the following characters up to a newline to be ignored.

INTERACTIVE_COMMENTS を有効にすると,histchars の3番目の文字(デフォルトは #)で始まる文字列について,その単語とその後の改行までの文字列がコメント扱いになり無視されるようになります.

histchars

% echo $histchars
!^#

# が三番目の文字であることがわかります.

Warning
  • histchars 特殊変数の設定は絶対変えないこと

設定方法

current sessionでのみ有効化したい場合は

% setopt INTERACTIVE_COMMENTS

を実行します.

## 設定していない場合
% echo hello #world            
hello #world

## setopt INTERACTIVE_COMMENTS実行後
% echo hello #world          
hello
Noteインタラクティブシェル全般用の設定
  • インタラクティブシェル全般でコメントアウト機能Onにしたい場合は,.zshrc に記載します

設定の解除

設定の解除は以下のコマンドを実行します

% unsetopt INTERACTIVE_COMMENTS

コメントアウトのユースケース紹介

zsh では ctrl + R でreverse history searchが実行できます.過去の実行コマンドを検索したい場合,コメントアウト機能と組み合わせると簡単に目的コマンドを探せるのでとても便利です.

seach word expected command
poetry-preview poetry run quarto preview
quarto vanilla preview quarto preview
apt-update sudo apt update && sudo apt upgrade -y