views:

68

answers:

4

Hi there, I'm trying to write a simple bash script but something seems wrong, I'm testing the following on the command line:

DATE="2010-09-{10,11}"
result=`\ls *ext.$DATE.Z`

and results in ls: cannot access *ext.2010-09-{10,11}.Z: No such file or directory

but if I execute this:

result=`\ls *ext.2010-09-{10,11}.Z`

it works flawlessly...

I even tried to remove the quotation marks from DATE parameter but that isn't the problem, bash manual isn't helping, what am I doing wrong? Wasn't it supposed to execute parameter substitution and pass it to my command?

I thought I should have to escape the $ sign but that didn't work either.

EDIT - Explanation on purpose added

What I am trying to accomplish is to populate variable result with all filenames that match the given pattern (*ext.2010-09-{10,11}), I know I can solve this using a for cycle but I thought about using curly braces for shortness.

+4  A: 

The issue is when you execute it directly on the command line \ls *ext.2010-09-{10,11}.Z is a short form that's expanded into two commands: ls *ext.2010-09-10.Z and ls *ext.2010-09-11.Z (by the command line - each subsequently called). ls itself doesn't directly support an expression like that, so when you build it into a script, it's getting the literal string which it doesn't understand.

Brace Expansion is not supported by all command lines, and isn't recommended for shell scripts:

Brace expansions should not be used in portable shell scripts, because the Bourne shell will not produce the same output.

Here's a solution-script:

#!/bin/sh
DAYS="10 11"
for i in $DAYS;
do
  ls *ext.2010-09-$i.Z
done
Rudu
Correct, your post completes my short explanation. Regards
Giuseppe Guerrini
Your answer is close but not quite correct. See mine.
Daenyth
Mhhh I guess I screwed up badly then, thankyou :)
Lex
But the question is tagged [bash] not [sh] or [bourne] and if you have a shebang that says `#!/bin/bash` you ought to be able to use Bash features.
Dennis Williamson
More or less that's what I did to solve it.
Lex
+1  A: 

The {x,y} group is not expanded anymore if you assign it to a variabile. But you can compose a string like "ls ..." and submit it to the "eval" function. Bye!

Giuseppe Guerrini
`eval` is unsafe and could potentially introduce security holes. There's probably a better way
Daenyth
+2  A: 

This happens because brace expansion happens before variable expansion. First it expands the braces -- except there are none in your argument to ls. Then it expands the variables. Then it runs it. At this point it's too late to expand the braces.

If you elaborate on the specific problem you're trying to solve I might be able to help you find a better way.

Daenyth
A: 

This will put the filenames you're looking for in the variable:

result=$(echo *ext.2010-09-{10,11}.Z)
Dennis Williamson