Block Comments in a Shell Script

后端 未结 12 1111
小鲜肉
小鲜肉 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:03

    You could use Vi/Vim's Visual Block mode which is designed for stuff like this:

    Ctrl-V  
    Highlight first element in rows you want commented  
    Shift-i  
    #  
    esc  
    

    Uncomment would be:

    Ctrl-V  
    Highlight #'s  
    d  
    l  
    

    This is vi's interactive way of doing this sort of thing rather than counting or reading line numbers.

    Lastly, in Gvim you use ctrl-q to get into Visual Block mode rather than ctrl-v (because that's the shortcut for paste).

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

    In bash:

    #!/bin/bash
    echo before comment
    : <<'END'
    bla bla
    blurfl
    END
    echo after comment
    

    The ' and ' around the END delimiter are important, otherwise things inside the block like for example $(command) will be parsed and executed.

    For an explanation, see this and this question.

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

    In Vim:

    1. go to first line of block you want to comment
    2. shift-V (enter visual mode), up down highlight lines in block
    3. execute the following on selection :s/^/#/
    4. the command will look like this:

        :'<,'>s/^/#
      
    5. hit enter

    e.g.

    shift-V
    jjj
    :s/^/#
    <enter>
    
    0 讨论(0)
  • 2020-12-02 04:07

    Another mode is: If your editor HAS NO BLOCK comment option,

    1. Open a second instance of the editor (for example File=>New File...)
    2. From THE PREVIOUS file you are working on, select ONLY THE PART YOU WANT COMMENT
    3. Copy and paste it in the window of the new temporary file...
    4. Open the Edit menu, select REPLACE and input as string to be replaced '\n'
    5. input as replace string: '\n#'
    6. press the button 'replace ALL'

    DONE

    it WORKS with ANY editor

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

    Use : ' to open and ' to close.

    For example:

    : '
    This is a
    very neat comment
    in bash
    '
    

    This is from Vegas's example found here

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

    The following should work for sh,bash, ksh and zsh.

    The blocks of code to be commented can be put inside BEGINCOMMENT and ENDCOMMENT:

    [ -z $BASH ] || shopt -s expand_aliases
    alias BEGINCOMMENT="if [ ]; then"
    alias ENDCOMMENT="fi"
    
    BEGINCOMMENT
      echo "This line appears in a commented block"
      echo "And this one too!"
    ENDCOMMENT
    
    echo "This is outside the commented block"
    

    Executing the above code would result in:

    This is outside the commented block
    

    In order to uncomment the code blocks thus commented, say

    alias BEGINCOMMENT="if : ; then"
    

    instead of

    alias BEGINCOMMENT="if [ ]; then"
    

    in the example above.

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