1

While this code works

#!/bin/bash
d="test_files/*"
for f in $d.{mp3,txt} ;do
do something 
done

putting the {mp3,txt} in to a variable does not, see code below.

#!/bin/bash
a={mp3,txt}
d="test_files/*"
for f in $d."$a" ;do
do smoething
done

the output here is /*.{mp3,txt}

Putting {mp3,txt} in to an array

a=({mp3,txt})

outputs only files with the *.mp3 extension.

5
  • 1
    What is your question? Commented Mar 15, 2013 at 16:27
  • The second example fails because brace expansion occurs prior to parameter expansion, so the braces are treated literally. The third example fails because a is an array of two elements, and $a expands to only the first (it's equivalent to ${a[0]}). Commented Mar 15, 2013 at 16:40
  • Remove the quotation marks around "$a". They stop bash from expanding the braces. When you have an array "a" then "$a" will evaluate to the first item. For all items use "${a[@]}". Also: read "man bash" Commented Mar 15, 2013 at 16:40
  • Using the "${a[@]}" in the loop "for f in $d.${a[@]}", fails all so. Commented Mar 16, 2013 at 13:18
  • It iterates $d.$a[0], giving me the all the mp3 files. on a[1], the out put is just "txt". I solved it with 2 for loop, the first iterating the "$a" array and the second iterating "$d" argument. Still if anybody has any ideas how to do this with one loop, i'm still interested. Commented Mar 16, 2013 at 13:23

1 Answer 1

1

It doesn't work because brace expansion happens before all other expansions.

From man bash:

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. To avoid conflicts with parameter expansion, the string ‘${’ is not considered eligible for brace expansion

You can use eval to do brace expansion stored in variables, but it is not recommended. For example:

eval echo "$d.$a"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation, the tutorial i'm using did not mention brace expansion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.