如何评论 bash 中的参数列表
How to comment list of arguments in bash
如何注释函数的参数列表?我想做这样的事情,但行不通:
my_func \
# This is for something
arg_1 \
\
# This is for something else
arg_2 \
\
# This is not not for anything
arg_3
这显然行不通。有什么办法可以实现这样的目标吗?下一个选项是这样的:
my_func \
arg_1 \ # This is for something
arg_2 \ # This is for something else
arg_3 # This is not not for anything
这在我看来不太理想,但也行不通。有什么想法吗?
问题归结为 "how do I make an inline comment in bash",技术上正确的答案是你不能。但是,您可以 近似 内联注释,如 this answer.
所示
所以这样做的方法(不是没有开销,但它是最接近我想要的)是:
my_func \
arg_1 `# This is for something` \
arg_2 `# This is for something else` \
arg_3 # This is not not for anything
或者
my_func \
`# This is for something` \
arg_1 \
\
`# This is for something else` \
arg_2 \
\
`# This is not not for anything` \
arg_3
使用命令替换作为假评论既昂贵(您仍然必须分叉 shell 并解析评论)又可能很危险(命令替换可以嵌套,但仍会执行)。更好的方法是将参数存储在一个数组中,这样就不会无意中执行。
args=(
# This is for something
arg_1
# This is for something else
arg_2
# This is not not for anything
arg_3
)
my_func "${args[@]}"
如果您需要保持 POSIX 兼容,即没有数组,我建议在调用之前简单地记录参数:
# Arg 1: this is for something
# Arg 2: this is for something else
# Arg 3: this is not for anything
my_func \
arg_1 \
arg_2 \
arg_3
这有效,并且对性能的影响很小,但它并不漂亮:
my_func \
${IFS# This is for something } \
arg_1 \
\
${IFS# This is for something else } \
arg_2 \
\
${IFS# This is not not for anything } \
arg_3
如何注释函数的参数列表?我想做这样的事情,但行不通:
my_func \
# This is for something
arg_1 \
\
# This is for something else
arg_2 \
\
# This is not not for anything
arg_3
这显然行不通。有什么办法可以实现这样的目标吗?下一个选项是这样的:
my_func \
arg_1 \ # This is for something
arg_2 \ # This is for something else
arg_3 # This is not not for anything
这在我看来不太理想,但也行不通。有什么想法吗?
问题归结为 "how do I make an inline comment in bash",技术上正确的答案是你不能。但是,您可以 近似 内联注释,如 this answer.
所示所以这样做的方法(不是没有开销,但它是最接近我想要的)是:
my_func \
arg_1 `# This is for something` \
arg_2 `# This is for something else` \
arg_3 # This is not not for anything
或者
my_func \
`# This is for something` \
arg_1 \
\
`# This is for something else` \
arg_2 \
\
`# This is not not for anything` \
arg_3
使用命令替换作为假评论既昂贵(您仍然必须分叉 shell 并解析评论)又可能很危险(命令替换可以嵌套,但仍会执行)。更好的方法是将参数存储在一个数组中,这样就不会无意中执行。
args=(
# This is for something
arg_1
# This is for something else
arg_2
# This is not not for anything
arg_3
)
my_func "${args[@]}"
如果您需要保持 POSIX 兼容,即没有数组,我建议在调用之前简单地记录参数:
# Arg 1: this is for something
# Arg 2: this is for something else
# Arg 3: this is not for anything
my_func \
arg_1 \
arg_2 \
arg_3
这有效,并且对性能的影响很小,但它并不漂亮:
my_func \
${IFS# This is for something } \
arg_1 \
\
${IFS# This is for something else } \
arg_2 \
\
${IFS# This is not not for anything } \
arg_3