0

I have directories a1..a5, b1..b5 and c1..c5. Inside each directory I have two files a1, b1 and c1.

do mkdir /tmp/{a,b}$d; touch /tmp/{a,b,c}$d/{a,b,c}1; done;

I want to get all the files starting with 'a' or 'b' inside the directories starting with an 'a'. I can do it with:

DIRS=`ls -1 -d /tmp/{a,b}*/a*`
echo ${DIRS}

and obtain:

/tmp/a1/a1 /tmp/a2/a1 /tmp/a3/a1 /tmp/a4/a1 /tmp/a5/a1 /tmp/b1/a1 /tmp/b2/a1 /tmp/b3/a1 /tmp/b4/a1 /tmp/b5/a1

Now, I will use a variable called DATA to store the directories and later get the files:

DATA="/tmp/{a,b}*"
echo ${DATA}
DIRS=`ls -1 -d ${DATA}/a*`
echo ${DIRS}

In the output, the DATA contents is OK (/tmp/{a,b}*), but I receive the following error:

ls: cannot access /tmp/{a,b}*/a*: No such file or directory

Any idea why this happens?

Jose Raul Barreras
  • 849
  • 1
  • 13
  • 19

1 Answers1

1

I solved the problem, but I can't find any reference about why my previous attempts failed.

DATA="/tmp/{a,b}*"
echo ${DATA}
DIRS=`eval "ls -1 -d ${DATA}/a*"`
echo ${DIRS}

Output:

/tmp/a1/a1 /tmp/a2/a1 /tmp/a3/a1 /tmp/a4/a1 /tmp/a5/a1 /tmp/b1/a1 /tmp/b2/a1 /tmp/b3/a1 /tmp/b4/a1 /tmp/b5/a1

Jose Raul Barreras
  • 849
  • 1
  • 13
  • 19
  • 1
    This happens because glob and brace expansion don't happen in double quotes or string assignments, while glob expansion does happen after word splitting. This means that if you do `echo something` vs `var=something; echo $var`, both will end up expanding globs but only the former will end up expanding braces. – that other guy Jul 27 '16 at 23:27