4

I want to comment parts of a bash for loop argument list. I would like to write something like this, but I can't break the loop across multiple lines. Using \ doesn't seem to work either.

for i in
  arg1 arg2     # Handle library
  other1 other2 # Handle binary
  win1 win2     # Special windows things
do .... done;
codeforester
  • 39,467
  • 16
  • 112
  • 140
Chris Jefferson
  • 7,225
  • 11
  • 43
  • 66
  • You should be able to use the \ to escape a linefeed. Just make sure there are no trailing spaces after it, otherwise, you are escaping a space. However, you will not be able to comment out arguments like you can with codeforester's solution. – Jason May 23 '18 at 18:32
  • 2
    @jason: doesn't work inside comments, I'm afraid – rici May 23 '18 at 18:35
  • 1
    @codeforester , I rolled back your edit to the question title, it didn't line up with the actual content of the question, or the answers. – Chris Jefferson May 26 '18 at 13:00

2 Answers2

6

You can store your values in an array and then loop through them. The array initialization can be interspersed with comments unlike line continuation.

values=(
    arg1 arg2     # handle library
    other1 other2 # handle binary
    win1 win2     # Special windows things
)
for i in "${values[@]}"; do
    ...
done

Another, albeit less efficient, way of doing this is to use command substitution. This approach is prone to word splitting and globbing issues.

for i in $(
        echo arg1 arg2     # handle library
        echo other1 other2 # handle binary
        echo win1 win2     # Special windows things
); do
  ...
done

Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140
1

In the code beneath I do not use handlethings+=, it will be too easy to forget a space.

handlethings="arg1 arg2"                     # Handle library
handlethings="${handlethings} other1 other2" # Handle binary
handlethings="${handlethings} win1 win2"     # Special windows things

for i in ${handlethings}; do
   echo "i=$i"
done
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • This has word splitting and globbing issues, just like the second solution in my [answer](https://stackoverflow.com/a/50495101/6862601). – codeforester May 25 '18 at 21:34