2

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?

3
  • 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. – schily Jan 15 '20 at 14:41
  • 1
    Another exception is the shebang line (characters hash sign and exclamation mark (#!)) at the beginning of scripts. – Paulo Tomé Jan 15 '20 at 14:59
  • 1
    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. – mosvy Jan 15 '20 at 21:32
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. – schily Jan 15 '20 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 #.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.