Bash – Why does “cat {foo}” not output foo, but “cat {foo,bar}” does

bashbrace-expansioncat

I was trying to concatenate text files in sub-folders and tried:

cat ./{mainfolder1,mainfolder2,mainfolder3}/{subfolder1}/book.txt > out$var

However this did not return anything. So, tried adding a non existing 'subfolder2'

cat ./{mainfolder1,mainfolder2,mainfolder3}/{subfolder1,subfolder2}/book.txt > out$var

And this time it did work out, concatenating the files successfully.
Why does this happens?

Best Answer

By definition, brace expansion in GNU Bash requires either a sequence expression or a series of comma-separated values:

Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript.

You can read the manual for details.

A few simple samples:

echo {subfolder1}
{subfolder1}

echo {subfolder1,subfolder2}
subfolder1 subfolder2

echo subfolder{1}
subfolder{1}

echo subfolder{1..2}
subfolder1 subfolder2
Related Question