Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brace expansion with a Bash variable - {0..$foo}

WEEKS_TO_SAVE=4
mkdir -p weekly.{0..$WEEKS_TO_SAVE}

gives me a folder called weekly.{0..4}

Is there a secret to curly brace expansion while creating folders I'm missing?

like image 936
xref Avatar asked Feb 18 '12 00:02

xref


2 Answers

bash does brace expansion before variable expansion, so you get weekly.{0..4}.
Because the result is predictable and safe(Don't trust user input), you can use eval in your case:

$ WEEKS_TO_SAVE=4
$ eval "mkdir -p weekly.{0..$((WEEKS_TO_SAVE))}"

note:

  1. eval is evil
  2. use eval carefully

Here, $((..)) is used to force the variable to be evaluated as an integer expression.

like image 99
kev Avatar answered Sep 19 '22 15:09

kev


Curly braces don't support variables in BASH, you can do this:

 for (( c=0; c<=WEEKS_TO_SAVE; c++ ))
 do
    mkdir -p weekly.${c}
 done
like image 38
anubhava Avatar answered Sep 18 '22 15:09

anubhava