Search code examples
linuxbashvariablescommand-substitution

Twice Bash command substitution


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?


Solution

  • 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