最近、私は以前に見たことのない種類の複数行コメントを偶然発見しました。以下はサンプルスクリプトです。
echo a
#
: aaa
: ddd
#
echo b
これはうまくいくようです。構文vim
の強調も動作します。このようなコメントスタイルを何と呼びますか?これに関する追加情報をどのように見つけることができますか?
ベストアンサー1
これは複数行のコメントではありません。 #
一行コメントです。
:
(コロン)まったくコメントではなく、シェル組み込みコマンドです。いいえ、何もせずにtrueを返すnull演算ですtrue
(したがって$?
副作用として0に設定されます)。しかし、コマンドなので引数を受け入れることができ、引数を無視するので、ほとんどの場合、表面的にはコメントのように動作します。今回のパッチワークの主な問題点は、議論が拡大し続け、意図しない結果が多く出てくることです。パラメータは依然として構文エラーの影響を受け、リダイレクトは引き続き実行されるため切り捨てられ、代替エントリは引き続き: > file
実行file
さ: $(dangerous command)
れます。
シェルスクリプトにコメントを挿入する最も驚くほど完全に安全な方法は、#
複数行のコメントにもこれを使用することです。 いいえコメントを(ab)お試しください:
。/* */
同様の言語のスラッシュ - アスタリスク形式に似た専用の複数行コメントメカニズムがシェルにありません。C
完全性のためにこれが推奨される方法ではないので、次のものを使用できると述べます。ここのドキュメント複数行の「コメント」を作成します。
: <<'end_long_comment'
This is an abuse of the null command ':' and the here-document syntax
to achieve a "multi-line comment". According to the POSIX spec linked
above, if any character in the delimiter word ("end_long_comment" in
this case) above is quoted, the here-document will not be expanded in
any way. This is **critical**, as failing to quote the "end_long_comment"
will result in the problems with unintended expansions described above.
All of this text in this here-doc goes to the standard input of :, which
does nothing with it, hence the effect is like a comment. There is very
little point to doing this besides throwing people off. Just use '#'.
end_long_comment