Inline comments for Bash?

前端 未结 8 833
深忆病人
深忆病人 2020-12-07 13:28

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:<

相关标签:
8条回答
  • 2020-12-07 13:56

    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
    
    0 讨论(0)
  • 2020-12-07 13:56

    How about storing it in a variable?

    #extraargs=-F
    ls -l $extraargs -a /etc
    
    0 讨论(0)
  • 2020-12-07 14:00

    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
    
    0 讨论(0)
  • 2020-12-07 14:01

    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.
    
    0 讨论(0)
  • 2020-12-07 14:03

    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

    0 讨论(0)
  • 2020-12-07 14:09

    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

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