Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to comment list of arguments in bash

How can I comment a list of arguments to a function? I'd like to do something like this, which does not work:

my_func \
  # This is for something
  arg_1 \
  \
  # This is for something else
  arg_2 \
  \
  # This is not not for anything
  arg_3

Which obviously doesn't work. Is there any way to achieve something like this? The next option would be something like this:

my_func \
  arg_1 \ # This is for something
  arg_2 \ # This is for something else
  arg_3 # This is not not for anything

Which is less desirable in my book but also does not work. Any ideas?

like image 376
ACK_stoverflow Avatar asked Dec 14 '25 02:12

ACK_stoverflow


2 Answers

Using command substitution as a fake comment is both expensive (you still have to fork a shell and parse the comment) and possibly dangerous (command substitutions can be nested, and those will still be executed). A better way is to store your arguments in an array where there is no chance of inadvertent execution.

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[@]}"

If you need to remain POSIX-compliant, meaning no arrays, I suggest simply documenting the arguments prior to the call:

# 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
like image 162
chepner Avatar answered Dec 15 '25 19:12

chepner


This works, and has minimal impact on performance, but it is not pretty:

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
like image 26
pjh Avatar answered Dec 15 '25 18:12

pjh