fny
fny

Reputation: 33517

Difference between : and # for Bash comments

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.

Upvotes: 7

Views: 87

Answers (2)

Soham
Soham

Reputation: 11

':' 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.

Upvotes: 1

that other guy
that other guy

Reputation: 123410

: 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

Upvotes: 9

Related Questions