对Bash的内联评论?

Laj*_*agy 133 bash comments

我希望能够在一行命令中注释掉一个标志.Bash似乎只有from # till end-of-line评论.我正在看这样的技巧:

ls -l $([ ] && -F is turned off) -a /etc
Run Code Online (Sandbox Code Playgroud)

它很难看,但总比没有好.有没有更好的办法?

以下似乎有效,但我不确定它是否可移植:

ls -l `# -F is turned off` -a /etc
Run Code Online (Sandbox Code Playgroud)

Raf*_*ino 100

我的首选是:

评论Bash脚本

这将有一些开销,但从技术上讲它确实回答了你的问题

echo abc `#put your comment here` \
     def `#another chance for a comment` \
     xyz etc
Run Code Online (Sandbox Code Playgroud)

特别是对于管道,有一个更清洁的解决方案,没有开销

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
Run Code Online (Sandbox Code Playgroud)

如何为多行命令添加行注释

  • 请注意,你必须使用反引号,`$(#comment)`不起作用. (3认同)
  • 某些版本会将 `)` 视为评论本身的一部分。bash 的大部分挑战是由于与旧版本的复古兼容性,一种常见的策略是尽可能使用最旧的解决方案。 (2认同)
  • 注意,这不是真正的注释:`true && \`# comment\` && true` 是一个有效的表达式。真正的评论会产生类似的东西:`靠近意外标记`&&'`的语法错误 (2认同)

Dan*_*Dan 56

我发现只复制该行并注释掉原始版本是最简单的(也是最可读的):

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

  • 但它不是内联的?我想可以公平地说,需要做 bash 不支持的事情是导致找到另一种方式的原因 (4认同)

Ign*_*ams 23

$(: ...) 有点不那么难看,但仍然不好.

  • 使用 ${IFS#...} 不会调用子 shell。 (4认同)
  • @Rafareino:是的 但严重的是,在95%的应用程序中,这种开销根本不重要.对于许多重要的情况,首先使用比Bash更快的语言可能是个好主意. (3认同)
  • 通过这种语法,您将触发一个子shell,可以通过注释来改善可扩展性,而根本不改变代码的行为,但是启动/结束该子shell的时间会使您的代码变慢(至少可以这样说),为什么不在新行的开头仅使用冒号? (2认同)

Kyl*_*vis 6

这是我针对多个管道命令之间的内联注释的解决方案。

未注释代码示例:

    #!/bin/sh
    cat input.txt \
    | grep something \
    | sort -r
Run Code Online (Sandbox Code Playgroud)

管道注释的解决方案(使用辅助函数):

    #!/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
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意,这里是没有帮助函数的相同解决方案,但它有点混乱:

    #!/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
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果您将管道字符移动到上一行的末尾,您可以摆脱令人讨厌的反斜杠换行符。 (8认同)