2017-09-23 71 views
7

今天我看到一個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

':'是一個shell內置命令,它除了展開參數並返回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