LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   Bash - brace expansion using variable (http://www.linuxquestions.org/questions/linux-software-2/bash-brace-expansion-using-variable-797598/)

student04 03-24-2010 01:03 PM

Bash - brace expansion using variable
 
I'm trying to use brace expansion on a string, but I can't seem to get it working with variable substitution:

Code:

$ cat script.sh
#!/bin/bash

echo {1,2,3} # 1.

VAR=1,2,3
echo {$VAR} # 2.

Code:

$ sh script.sh
1 2 3
{1,2,3}

I've searched google, tldp.org and these forums and I can't seem to find an example of how this would work. I want #2 to work like #1. Any suggestions?

**Edit: I forgot to add, the values in VAR are not sequential and can have multiple digits. For example, VAR=13,17,10.

**Edit2: http://tldp.org/LDP/abs/html/bashver3.html#BRACEEXPREF3
The bottom line of code in the first gray block of code shows that you cannot use variables in such an expansion:

Code:

#!/bin/bash
a=1
b=5
echo {$a..$b}

But I'm looking for pasting the complete contents of a variable into these braces, not some portion of it...

Thanks,
Alex

Kenhelm 03-24-2010 01:42 PM

Try using the bash builtin 'eval' to do a double expansion on the expression.
It needs to be used carefully as it can sometimes expand special characters which you don't want expanding.
Code:

VAR=1,2,3
eval echo {$VAR}
1 2 3

a=1
b=5
eval echo {$a..$b}
1 2 3 4 5


student04 03-24-2010 02:26 PM

Actually, I had considered 'eval' but wasn't sure actually how to make that work... Thanks :) I have a bunch of files in a directory that I needed listed and stored in a variable, but want the pattern to be separate (code is more legible):

Code:

$ cat script.sh
PATTERN=12,14,27
FILES=$(eval ls filename_{$PATTERN})
echo $FILES

$ sh script.sh
filename_12 filename_14 filename_27



All times are GMT -5. The time now is 07:43 PM.