bash/shell script comment multiple lines of code

Recently I got to know about how to comment multiple lines in shell/bash scripts.

I will show an example to comment multiple lines of code in bash/shell script.

Following are lines of code in my script test.sh

#!/bin/bash
echo a
echo b
echo c
echo d
echo f

The out put we can get after executing script test.sh is shown below:

a

b

c

d

e

f

If we want to print only a and f, we need to comment multiple lines of code in script test.sh. Traditionally we use “#” to comment a single line of code in shell/bash.

To comment multiple lines code you need to add <<COMMENT and COMMENT tags. The code between this to tags will be commented.

The code in test.sh after adding comment tags will looks like below.

#!/bin/bash
echo a
<<COMMENT
echo b
echo c
echo d
COMMENT
echo f

Now execute the script test.sh and the output you will get output as shown below:

a

f

 -Sany

About these ads

7 comments on “bash/shell script comment multiple lines of code

  1. Worth noting that the string COMMENT in the comments would unescape this also…

    << WIBBLEWOBBLEIMACOMMENT

    echo ¨blah¨

    WIBBLEWOBBLEIMACOMMENT

    would be also valid (and less likely to ever get an accidental clash)

    • The reason I used word COMMENT is it’s easy to remember and apt for this scenario. You can use any word instead using COMMENT, it should work without any issue.

  2. It cannot work with the following code:
    —————————————-
    echo ‘a’
    <<COMMENT
    echo 'b'
    echo 'c'
    $(grep 'igotu' non_existed_file)
    COMMENT
    echo 'e'
    —————————————–
    the output is:
    a
    grep: non_existed_file: No such file or directory
    e
    instead of
    a
    e
    —————————————
    the result shows that the grep statement in the $(..) is still executed by the shell, and this is totally not what we expected with the comment.
    It seems the comment failed with the $(…) statement.

    the above code is tested in:
    CentOS release 6.3 (Final)
    GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

    anybody know why?
    :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s