簡體   English   中英

如何在 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

這在我的書中不太理想,但也不起作用。 有任何想法嗎?

使用命令替換作為假注釋既昂貴(你仍然需要 fork 一個 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

問題歸結為“我如何在 bash 中進行內聯注釋”,技術上正確的答案是您不能。 但是,您可以近似內聯注釋,如本答案所示。

所以這樣做的方法(不是免費的,但它是最接近我想要的)是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM