Given a string variable (not a string) in bash, how can one expand its curly braces (and glob any file wildcards like asterisks), and then store the resulting expansion in an array?
I know this is possible with eval
:
#!/usr/bin/env bash
string="{a,b}{1,2}"
array=( $( eval echo $string ) )
echo "${array[@]}"
#a1 a2 b1 b2
But eval
could be dangerous if we don't trust the contents of string
(say, if it is an argument to a script). A string
with embedded semicolons, quotes, spaces, arbitrary commands, etc. could open the script to attack.
Is there a safer way to do this expansion in bash? I suspect that all of the following are equally unsafe ways of expanding the string:
#!/usr/bin/env bash
eval echo $string
bash <<< "echo $string"
echo echo $string | bash
bash <(echo echo $string)
Is there perhaps a command other than bash that we can pipe the string to, that would do the expansion?
Aside: Note that in csh/tcsh this is easy, since brace expansion happens after variable substitution (unlike in bash):
#!/usr/bin/env csh
set string = "{a,b}{1,2}"
set array = ( $string )
echo "$array"
#a1 a2 b1 b2