Difference between: and # for Bash comments

Today I saw that the bash script uses a colon to indicate a comment. What is the difference between using a colon and a hash tag?

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

First, I know that you cannot use a colon for a trailing comment:

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

But the fact that the above example works, I was puzzled by how it is estimated :

+7
bash
source share
2 answers

: is just an alias for true , and true ignores its arguments:

 # Does nothing: true foo bar etc hello # Does the same: : foo bar etc hello 

This is not a comment and should never be used as a comment because all its arguments are still parsed and evaluated:

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

or like here, where StackOverflow syntax highlighting determines that the command in the middle is actually just text, even if the person is not executing:

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

':' is a built-in shell command that does nothing but expand the arguments and return true . On the bash man page:

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

# is a comment. But it only works for single lines.

More information about the ":" command here you can read here and get the best answer here .

+1
source share

All Articles