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?
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?
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:
eval
is evileval
carefullyHere, $((..))
is used to force the variable to be evaluated as an integer expression.
$(rm -rf /)
or write to a file by including >/etc/passwd
... unless you use eval
, in which case that data is parsed as code. –
Synchronism $((..))
would force it do arithmetic expansion, but why do we have to use $((WEEKS_TO_SAVE))
instead of simple $WEEKS_TO_SAVE
, what could $WEEKS_TO_SAVE
potentially damage –
Anesthesia export n=10 ; for i in
eval echo {1..$n}` ; do echo $i.x ; done` or sticking the eval in with an echo. –
Aimo 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
Another way of doing it without eval and calling mkdir only once:
WEEKS_TO_SAVE=4
mkdir -p $(seq -f "weekly.%.0f" 0 $WEEKS_TO_SAVE)
Brace expansion does not support it. You will have to do it using a loop.
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
.
If you happen to have zsh
installed on your box, your code as written will work with Z-shell if you use #!/bin/zsh
as your interpreter:
$ WEEKS_TO_SAVE=4
$ echo {0..$WEEKS_TO_SAVE}
0 1 2 3 4
© 2022 - 2024 — McMap. All rights reserved.