Block Comments in a Shell Script

后端 未结 12 1112
小鲜肉
小鲜肉 2020-12-02 03:36

Is there a simple way to comment out a block of code in a shell script?

相关标签:
12条回答
  • 2020-12-02 04:15

    if you can dodge the single quotes:

    __='
    blah blah comment.
    '
    
    0 讨论(0)
  • 2020-12-02 04:19

    There is no block comment on shell script.

    Using vi (yes, vi) you can easily comment from line n to m

    <ESC>
    :10,100s/^/#/
    

    (that reads, from line 10 to 100 substitute line start (^) with a # sign.)

    and un comment with

    <ESC>
    :10,100s/^#//
    

    (that reads, from line 10 to 100 substitute line start (^) followed by # with noting //.)

    vi is almost universal anywhere where there is /bin/sh.

    0 讨论(0)
  • 2020-12-02 04:19

    I like a single line open and close:

    if [ ]; then ##
        ...
        ...
    fi; ##
    

    The '##' helps me easily find the start and end to the block comment. I can stick a number after the '##' if I've got a bunch of them. To turn off the comment, I just stick a '1' in the '[ ]'. I also avoid some issues I've had with single-quotes in the commented block.

    0 讨论(0)
  • 2020-12-02 04:20

    You can use:

    if [ 1 -eq 0 ]; then
      echo "The code that you want commented out goes here."
      echo "This echo statement will not be called."
    fi
    
    0 讨论(0)
  • 2020-12-02 04:21

    In all honesty, why so much overengineering...

    I consider it really a bad practice to write active code for generating passive code.

    My solution: most editors have block select mode. Just use it to add # to all lines you want to comment out. What's the big deal...

    Notepad example:

    To create: Alt - mousedrag down, press #.

    To delete: Alt-mousedrag down, shift-right arrow, delete.

    0 讨论(0)
  • 2020-12-02 04:21

    A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.

    As far as the shell is concerned, you only need to replace 'END' with '=cut'.

    echo "before comment"
    : <<'=cut'
    =pod
    
    =head1 NAME
       podtest.sh - Example shell script with embedded POD documentation
    
    etc.
    
    =cut
    echo "after comment"
    

    (Found on "Embedding documentation in shell script")

    0 讨论(0)
提交回复
热议问题