2017-09-23 14 views
7

今日、私はbashスクリプトがコメントを示すためにコロンを使用するのを見ました。コロンとハッシュマークの違いは何ですか? 1については違い:Bashのコメント#

: This is a comment. 
# This is also a comment. 

、私はあなたが末尾のコメントコロンを使用することはできません知っている:

cd somedir : This won't work as a comment. 

しかし、上記の例が機能するということは、:の評価方法について、私は困惑しています。

+1

関連記事を読むことができます。https://stackoverflow.com/questions/3224878/what-is-the-purpose-of-the-colon-gnu-bash-builtin – slevy1

+0

後ろにコメントするには、 ';:'を使用してください。ちょうど冗談を言って、「他の男の答え」を参照してください:-) – paxdiablo

答えて

9

:は単にtrueの別名である、とtrueは、その引数を無視します:

# Does nothing: 
true foo bar etc hello 

# Does the same: 
: foo bar etc hello 

それはコメントはありませんし、すべての引数は、まだ解析され、評価されているので、コメントとして使用すべきではありません。

: This "comment" actually executes this command: $(touch foo) 
ls -l foo 

などここでは、StackOverflowの構文強調表示では、人間がそうでない場合でも、真ん中のコマンドは実際にはテキストだけであることが分かります。

: The command below won't run: 
echo "Hello World" 
: because the surrounding "comments" each contain a ' characters 
1

':'は引数を展開してtrueを返すシェル組み込みコマンドです。 bash man pageから:

: [arguments] 
No effect; the command does nothing beyond expanding arguments 
and performing any specified redirections. A zero exit code is 
returned. 

#コメントです。しかし、それは単一行のためだけに機能します。

「:」コマンドhereとより良い回答hereについて詳しく読むことができます。