shell 如何为多行命令添加行注解[重复]

64jmpszr  于 2023-08-07  发布在  Shell
关注(0)|答案(4)|浏览(93)

此问题在此处已有答案

Commenting in a Bash script inside a multiline command(10个答案)
6年前关闭。
我知道如何在Bash脚本中编写多行命令,但如何为多行命令中的每一行添加注解?

CommandName InputFiles      \ # This is the comment for the 1st line
            --option1 arg1  \ # This is the comment for the 2nd line
            --option2 arg2    # This is the comment for the 3nd line

字符串
但不幸的是,在延续字符\之后的注解将中断该命令。

r7s23pms

r7s23pms1#

我就是这么做的本质上,通过使用Bash的反勾号command substitution,可以将这些注解放置在长命令行的任何位置,即使是跨行拆分。我把echo命令放在你的例子前面,这样你就可以执行这个例子,看看它是如何工作的:

echo CommandName InputFiles `#1st comment` \
             --option1 arg1 `#2nd comment` \
             --option2 arg2 `#3rd comment`

字符串
另一个例子,你可以把多个注解放在一行的不同位置:

some_cmd --opt1 `#1st comment` --opt2 `#2nd comment` --opt3 `#3rd comment`

aydmsdu9

aydmsdu92#

你可以将参数存储在一个数组中:

args=(
    InputFiles           # This is the comment for the 1st line
    --option1 arg1       # This is the comment for the 2nd line
    --option2 arg2       # This is the comment for the 3nd line
    #--deprecated-option # Option disabled
)
CommandName "${args[@]}"

字符串
你甚至可以添加空行来增强可读性:

args=(

    # This is the comment for the 1st line
    InputFiles

    # This is the comment for the 2nd line
    --option1 arg1

    # This is the comment for the 3nd line
    --option2 arg2

    # Option disabled
    #--deprecated-option

)
CommandName "${args[@]}"

jei2mxaa

jei2mxaa3#

我担心,一般来说,你不能做你所要求的。最好的方法是在命令前的行上添加注解,或者在命令行末尾添加一个注解,或者在命令后添加一个注解。
您无法通过这种方式在命令中散布注解。\表示合并行的意图,因此,出于所有意图和目的,您试图在单行中散布注解,这无论如何都不起作用,因为\必须位于行尾才能产生这种效果。

0h4hbjxa

0h4hbjxa4#

根据pjh对another answer to this question的注解,将IFS替换为已知不包含非空格字符的变量。

comment=
who ${comment# This is the command} \
    -u ${comment# This is the argument}

字符串
为什么参数展开式不加引号?变量用空字符串初始化。当参数展开时,#操作符(与shell注解字符#无关,但用于相似性)尝试从参数值中剥离实际注解。当然,结果仍然是一个空字符串。
未加引号的参数展开会进行字拆分和路径名生成。在这种情况下,两个进程都不会从空字符串创建任何额外的单词,因此结果仍然是空字符串。这样的空字符串将被简单地丢弃,而不会影响它出现的命令。上述内容正好相当于

who \
  -u

相关问题