Search code examples
bashparsingshcommentsinterpreter

Why can you not have comments in multi-line commands in sh?


I've looked at these posts:

but it doesn't answer conceptually why not.

For example:

#!/bin/bash

echo \
# comment
-n hello

on shellcheck.net yields:

-n hello ^-- SC2215 (warning): This flag is used as a command name. Bad line break or missing [ .. ]?

Reason I thought it would be okay:

  • I had learned comments are ignored by programs (and so it should make no difference)

For example, a C program:

#include <stdio.h>

int main() {

  printf("hello%d\n",
         // my comment
         3);
}

Why is this fundamentally different in bash and sh?

How is it being interpreted that causes this (with comments not being completely ignored by the interpreter)?

My idea:

  • the shell simply ignores lines with comments while parsing, but expects a continuation line after the backslash and for some reason (why?) breaks if a comment (which should be ignored) is there instead of looking at the next (uncommented) line
  • C compiler never even sees comments because they are gone by compilation stage

Solution

  • For POSIX shell, this behaviour is defined here in chapter 2.3 Token Recognition:

    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.

    bash simply took over this convention to make it easier to port scripts from sh to bash. From what I see, zsh is doing the same, and most likely ksh too.