Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash line continuation and comments

Tags:

bash

Any explanation why the comment is echo'ed in the third example?

$ echo a b \
> c # test
a b c

$ echo a b c \
> # test
a b c

$ echo a b c \
> \ # test
a b c  # test

$ echo a b c \
> \  # test
a b c 
like image 927
Harald Hoyer Avatar asked May 30 '18 16:05

Harald Hoyer


People also ask

How do you comment multiple lines in Shell?

In Shell or Bash shell, we can comment on multiple lines using << and name of comment. we start a comment block with << and name anything to the block and wherever we want to stop the comment, we will simply type the name of the comment.

How do I comment in a bash script?

When writing bash scripts, any text after a hash sign ( # ) indicates the start of a comment, and any text after # in the same line does not execute. When using a text editor or IDE, comments are colored differently from the rest of the code.

How do you comment multiple lines in Makefile?

' # ' in a line of a makefile starts a comment. It and the rest of the line are ignored, except that a trailing backslash not escaped by another backslash will continue the comment across multiple lines.


2 Answers

In bash, # starts a comment only if it is at the beginning of a word. As per this rule, neither of the following two command lines have comments:

$ echo a b c# test
a b c# test
$ echo a b c \ # test
a b c  # test

In the first case above, # is part of the word c# and # is not at the beginning.

In the second case above (your case), # is part of the word # (where the first character is a blank and # is the second character). # is not at the beginning and therefore does not start a comment.

Normally, the shell treats a blank as a word separator. By escaping the blank, it loses that special interpretation and becomes just another character.

The use or not of a continuation line does not change this.

Documentation

From the section entitled Comments in man bash:

a word beginning with # causes that word and all remaining characters on that line to be ignored. [Emphasis added.]

like image 149
John1024 Avatar answered Oct 14 '22 00:10

John1024


Seems like # test is the next word/argument and since comments have to start with # the third command has no comment.

like image 2
Harald Hoyer Avatar answered Oct 14 '22 00:10

Harald Hoyer