How to store curly brackets in a Bash variable

bash, brace-expansion

Solution

The expression

ls {*.xml,*.txt}

results in Brace expansion and shell passes the expansion (if any) to `ls` as arguments. Setting `shopt -s nullglob` makes this expression evaluate to nothing when there are no matching files.

Double quoting the string suppresses the expansion and shell stores the literal contents in your variable `name` (not sure if that is what you wanted). When you invoke `ls` with `$name` as the argument, shell does the variable expansion but no brace expansion is done.

As @Cyrus has mentioned, `eval ls $name` will force brace expansion and you get the same result as that of `ls {\*.xml,\*.txt}`.

Problem

I am trying to write a bash script. I am not sure why in my script: ``` ls {*.xml,*.txt} ``` works okay, but ``` name="{*.xml,*.txt}" ls $name ``` doesn't work. I get ``` ls: cannot access {*.xml,*.txt}: No such file or directory ```

Original source

Related problems