[bash] Inline comments for Bash?

I'd like to be able to comment out a single flag in a one-line command. Bash only seems to have from # till end-of-line comments. I'm looking at tricks like:

ls -l $([ ] && -F is turned off) -a /etc

It's ugly, but better than nothing. Is there a better way?

The following seems to work, but I'm not sure whether it is portable:

ls -l `# -F is turned off` -a /etc

This question is related to bash comments

The answer is


If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.

ls -l ${1# -F is turned off} -a /etc

§ 10.2. Parameter Substitution


I find it easiest (and most readable) to just copy the line and comment out the original version:

#Old version of ls:
#ls -l $([ ] && -F is turned off) -a /etc
ls -l -a /etc

Here's my solution for inline comments in between multiple piped commands.

Example uncommented code:

    #!/bin/sh
    cat input.txt \
    | grep something \
    | sort -r

Solution for a pipe comment (using a helper function):

    #!/bin/sh
    pipe_comment() {
        cat - 
    }
    cat input.txt \
    | pipe_comment "filter down to lines that contain the word: something" \
    | grep something \
    | pipe_comment "reverse sort what is left" \
    | sort -r

Or if you prefer, here's the same solution without the helper function, but it's a little messier:

    #!/bin/sh
    cat input.txt \
    | cat - `: filter down to lines that contain the word: something` \
    | grep something \
    | cat - `: reverse sort what is left` \
    | sort -r

My preferred is:

Commenting in a Bash script

This will have some overhead, but technically it does answer your question

echo abc `#put your comment here` \
     def `#another chance for a comment` \
     xyz etc

And for pipelines specifically, there is a cleaner solution with no overhead

echo abc |        # normal comment OK here
     tr a-z A-Z | # another normal comment OK here
     sort |       # the pipelines are automatically continued
     uniq         # final comment

How to put a line comment for a multi-line command


For disabling a part of a command like a && b, I simply created an empty script x which is on path, so I can do things like:

mvn install && runProject

when I need to build, and

x mvn install && runProject

when not (using Ctrl + A and Ctrl + E to move to the beginning and end).

As noted in comments, another way to do that is Bash built-in : instead of x:

$  : Hello world, how are you? && echo "Fine."
Fine.

Most commands allow args to come in any order. Just move the commented flags to the end of the line:

ls -l -a /etc # -F is turned off

Then to turn it back on, just uncomment and remove the text:

ls -l -a /etc -F

How about storing it in a variable?

#extraargs=-F
ls -l $extraargs -a /etc

$(: ...) is a little less ugly, but still not good.