如何为多行命令放行注释

我知道如何在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 

但是遗憾的是,继续angular色的评论会打破命令。

恐怕一般来说,你不能做你所要求的。 你可以做的最好的事情是对命令之前的行进行注释,或者在命令行结尾处注释一个注释,或者在命令之后注释。

你不能通过这种方式来在命令中散布注释。 \expression了合并行的意图,因此对于所有的意图和目的,您都试图将注释分散在单行中,但这并不起作用,因为\必须在行尾才能产生这种效果。

这是我如何做到的。 本质上,通过使用bash的backtick 命令replace,可以将这些注释放置在长命令行的任何位置,即使是跨行分割也是如此。 我已经把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` 

您可以将参数存储在数组中:

 args=(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 ) "${args[@]}" 

不过,我觉得这样做看起来有点冒失,只是为了让每一个论点都有评论。 因此,我只是重写注释,以便它引用个别的参数,并把它放在整个命令之上。

根据pjh对此问题的另一个答案的评论,用已知不包含非空白字符的variablesreplaceIFS

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