7

Today I saw a bash script use a colon to denote a comment. What's the difference between using a colon and a hash mark?

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

For one, I know you can't use a colon for a trailing comment:

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

But the fact that the above example works has me puzzled about how : is evaluated.

codeforester
  • 39,467
  • 16
  • 112
  • 140
fny
  • 31,255
  • 16
  • 96
  • 127
  • 1
    You may wish to read related discussion https://stackoverflow.com/questions/3224878/what-is-the-purpose-of-the-colon-gnu-bash-builtin – slevy1 Sep 23 '17 at 00:35
  • For a trailing comment, you need to use `;:`. Just kidding, see `that other guy`'s answer :-) – paxdiablo Sep 23 '17 at 00:52

2 Answers2

9

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

# Does nothing:
true foo bar etc hello

# Does the same:
: foo bar etc hello

It's 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's syntax highlighting picks up that the command in the middle is actually just text, even if a human doesn't:

: The command below won't run:
echo "Hello World"
: because the surrounding "comments" each contain a ' characters
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

':' is a shell builtin command which does nothing but expands arguments and returns true. From 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.

You can read more about ':' command here and a better answer here.

Soham
  • 11
  • 2