0

I want to use brace expansion to generate the following argument sequence: ./some_command -c root.foo -c root.bar -c root.baz. Brace expansion at first glance looks as a perfect tool: use -c root. as a preamble and {foo,bar,baz} inside braces. However, preamble cannot contain field separators:

  • ./some_command -c root.{foo,bar,baz} expands to -c root.foo root.bar root.baz (obviously)
  • ./some_command -c\ root.{foo,bar,baz} expands to -c\ root.foo -c\ root.bar -c\ root.baz (obviously again). Here I get three arguments instead of six desired.

Is it possible to make a preamble with an argument separator?

1 Answers1

0

You can concatenate brace expansions to get the cross product

echo ./some_command {"-c root."}{foo,bar,baz}

However

A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged.

-- https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion

So this might be OK

$ echo ./some_command {"-c root.",#}{foo,bar,baz}
./some_command -c root.foo -c root.bar -c root.baz #foo #bar #baz

The -c root.foo is considered a single word, so you might need to eval.

The best way to do this is to use arrays:

options=()
for arg in {foo,bar,baz}; do options+=( -c "root.$arg" ); done
echo ./some_command "${options[@]}"
glenn jackman
  • 26,306
  • 1
    I don't see the point of the first part of this answer. First you correctly notice that {"-c root."} in {"-c root."}{foo,bar,baz} does not expand, then you deal with this "problem" by introducing {"-c root.",#} which gives you words that start with #. They are not comments (your echo did print them), unless you eval the result. It so happens eval is a "solution" to the problem of -c root.foo being a single word, but the OP had this exact problem from -c\ root.{foo,bar,baz}. Why don't we just eval this? Why complicate things with the additional brace expansion and #? – Kamil Maciorowski Feb 19 '24 at 19:05