Echo Combinations with Special Character as Elements

I have a small script that takes advantage of echo's ability to generate combinations of elements. What a piece of code,

for ((i=0; i<$group; i++));

bash -c "echo "$repetition""


This works well, the problem occurs when I want the set to be composed of some special characters like commas, brackets, etc. I tried using scapes but it doesn't work, something like



Any hint on how to achieve it?


source to share

2 answers

You need to point and escape:



Note that it works with {1,2,3,4}

because these are numbers. For strings, you also need to specify:{1,2,3,'a'}

$ echo {1,2,3,'a'}{1,2,3,'a'}
11 12 13 1a 21 22 23 2a 31 32 33 3a a1 a2 a3 aa


And then the escaping has to handle the execution bash -c

along with the values.

From your comments, your final script:

for ((i=0; i<$group; i++));

bash -c "echo "$repetition""


When I complete it, I get it, good!

$ ./a
((( (() ((, ()( ()) (), (,( (,) (,, )(( )() )(, ))( ))) )), ),( ),) ),, ,(( ,() ,(, ,)( ,)) ,), ,,( ,,) ,,,




While @ fedorqui's answer is the way to go, here's a little more info for completeness. You know that special characters must be escaped, but \

this is a special character that must be escaped as well, since you are passing it to another bash instance.

So when you have it set={(,)}

in your script, your script will throw a syntax error due to parentheses. Once you leave them as set={\(,\)}

, your script is fine with them, but has already expanded them by the time you pass them to yours bash -c

, which will instead see set={( )}

and choke on it, giving the same syntax error:

$ set={\(,\)}; echo Parent: "$set";  bash -c "echo Child1: "$set""
Parent: {(,)}
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `echo Child1: {(,)}'


The obvious solution would be to avoid the backslashes themselves, so they will be passed in correctly. However, escaping causes the character to lose his special powers, so escaping \

will prevent him from escaping the parentheses:

$ set={\\(,\\)};
bash: syntax error near unexpected token `('


So, back to the square. What you need to do is an escape that eludes exit 1 :

$ set={\\\(,\\\)}
$ echo "Parent3: $set"
Parent3: {\(,\)}
$ bash -c "echo Child3 "$set""
Child3 ( )


Here, the child instance is finally transferred, that he needs to see: {\(,\)}

. Therefore, while it is not necessary to use quotes in such cases, they do make your life a lot easier:

1 Try saying that 5 times is fast.



All Articles