2017-09-23 33 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