views:

544

answers:

7

I was wondering if there is a way to comment out a set of lines in a shell script. How could I do that? We can use /* */ in other programming languages. This is most useful when I am converting/using/modifying another script and I want to keep the original lines instead of deleting.

It seems a cumbersome job to find and prefix # for all the lines which are not used.

Lets say there are 100 lines in the script in consequent lines which are not to used. I want to comment them all out in one go. Is that possible?

A: 

Take a look at the following: http://kunaljain.wordpress.com/2008/01/22/usefull-vi-tricks/

AlberT
A: 

Depending of the editor that you're using there are some shortcuts to comment a block of lines.

Another workaround would be to put your code in an "if (0)" conditional block ;)

Carlos Tasada
+4  A: 

Text editors have an amazing feature called search and replace. You don't say what editor you use, but since shell scripts tend to be *nix, and I use VI, here's the command to comment lines 20 to 50 of some shell script:

:20,50s/^/#/
kdgregory
That is ninja.
Tom Ritter
That's how I would do it. To uncomment, try this: :20,50s/^#//
Hai Vu
+1  A: 
if false
then

...code...

fi

false always returns false so this will always skip the code.

Artelius
bash is not a pre-processed language... this trick is useful when used in C as a preprocessor command. If you do it as you suggested you can't avoid possible syntax errors.
AlberT
I actually don't mind being informed of syntax errors in code that is "disabled".
Artelius
:/ This is certainly not the best answer, IMO.
Artelius
+9  A: 

You can use a 'here' document with no command to send it to.

#!/bin/bash
echo "Say Something"
<<COMMENT1
    your comment 1
    comment 2
    blah
COMMENT1
echo "Do something else"

Wikipedia Reference

Buggabill
A: 

This Perl one-liner comments out lines 1 to 3 of the file orig.sh inclusive (where the first line is numbered 0), and writes the commented version to cmt.sh.

perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

Obviously you can change the boundary numbers as required.

If you want to edit the file in place, it's even shorter:

perl -in -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh

Demo

$ cat orig.sh 
a
b
c
d
e
f

$ perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh

$ cat cmt.sh 
a
#b
#c
#d
e
f
ire_and_curses
A: 
: || {
your code here
your code here
your code here
your code here
}
jj_5698