3

There exist shell scripts where comments have a space between the hash sign and the actual comment

# a comment at the beginning of a line echo foo # a comment trailing after a command 

and other that do not have one

#another comment at the beginning of a line echo bar #another comment trailing after a command 

Does this decision have some sort of impact on the actual execution of the scripts or is it (just) a coding style issue?

4
  • 1
    After you enabled hashcommands via set -o hashcmds for recent Bourne Shell versions, A line that starts with #something is seens as a special command. But this only applies to the end of the file $HOME/.shrc where this feature is usually enabled for interactive shells. The default for all scripts is disabled hash commands. BTW: hash commands include a method to edit shell aliases witout a need to quote the text. Commented Jan 15, 2020 at 14:41
  • 2
    Another exception is the shebang line (characters hash sign and exclamation mark (#!)) at the beginning of scripts. Commented Jan 15, 2020 at 14:59
  • 2
    One big difference between the shell and other languages like awk or perl is that there should be a space or non-word token before the # in order to be recognized as a comment marker: echo 3#foo will print 3#foo not just 3. Commented Jan 15, 2020 at 21:32
  • @schily I can't find any information about set -o hashcmds at gnu.org/s/bash/manual/html_node/The-Set-Builtin.html or Google. Do you have any link where I can learn more about it? Commented Mar 15, 2024 at 15:23

2 Answers 2

4

There’s no non-stylistic difference; POSIX specifies that, when recognising tokens in the shell,

If the current character is a '#', it and all subsequent characters up to, but excluding, the next <newline> shall be discarded as a comment. The <newline> that ends the line is not considered part of the comment.

1
  • This is only true as long as you do not use POSIX extensions, see my comment on the original question. Commented Jan 15, 2020 at 14:43
3

I'm not aware of any shell in which a whitespace would matter. For example, in man bash it says:

 In a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled (see SHELL BUILTIN COMMANDS below), a word beginning with # causes that word and all remaining characters on that line to be ignored. 

It specifically says that all characters after # are ignored.

Personally, I prefer to put a whitespace after #.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.