[unix] Commenting out a set of lines in a shell script

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?

This question is related to unix shell comments editing

The answer is


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/^/#/

You can also put multi-line comments using:

: '
comment1comment1
comment2comment2
comment3comment3
comment4comment4
'

As per the Bash Reference for Bourne Shell builtins

: (a colon)

: [arguments]

Do nothing beyond expanding arguments and performing redirections. The return status is zero.

Thanks to Ikram for pointing this out in the post Shell script put multiple line comment


: || {
your code here
your code here
your code here
your code here
}

What if you just wrap your code into function?

So this:

cd ~/documents
mkdir test
echo "useless script" > about.txt

Becomes this:

CommentedOutBlock() {
  cd ~/documents
  mkdir test
  echo "useless script" > about.txt
}

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


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

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 ;)


The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.


As per this site:

#!/bin/bash
foo=bar
: '
This is a test comment
Author foo bar
Released under GNU 
'

echo "Init..."
# rest of script

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to comments

Way to create multiline comments in Bash? Jenkins: Can comments be added to a Jenkinsfile? /** and /* in Java Comments Where is the syntax for TypeScript comments documented? Multiple line comment in Python How do I add comments to package.json for npm install? How to comment multiple lines with space or indent Is there a shortcut to make a block comment in Xcode? How to comment and uncomment blocks of code in the Office VBA Editor Which comment style should I use in batch files?

Examples related to editing

Disabling user input for UITextfield in swift vim line numbers - how to have them on by default? "Find next" in Vim Commenting out a set of lines in a shell script Find a line in a file and remove it How to insert text at beginning of a multi-line selection in vi/Vim