Your script doesn't work the way you expect it because of the order of expansion.
From the bash manual:
The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.
As you see, brace expansion is first, variable expansion is later. In an assignment, brace expansion is not performed. Otherwise an expression x={1,2}
would be expanded to x=1 x=2
, and that also wouldn't make sense.
One solution for this, as you found out, is eval
, because the whole expansion is done twice, so the first variable expansion is performed before the second brace expansion.
Be sure you understand the risks of eval
, in particular never use it for untrusted input.
As you are using bash, you can use an array.
files=( ./*"$pattern"I{"$ifirst".."$ilast"}.ext )
cp "${files[@]}" ../"$pattern"/"$i"/
#!/bin/bash
and run withbash script.sh
.Had to addeval
to get it going. I had to fix an issue in getting it to respect leading zeros, but got it sorted. Thank you!