As millgates said, brace expansion with a variable doesn't work because the braces are expanded before the variable.
Bash Pitfall #33
brace expansion
You're generally much better off using a loop of some kind, as posted above. Although here's another technique you can use with only bash built-ins:
Code:
x=5
printf -v repvar '%0*d' "$x"
printf '%b' "${repvar//0/hi\n}"
The first
printf generates a string of zeros equal in length to the input number. The '
*' in the format string takes the first (and only) argument as the padding number to use, instead of printing it directly.
printf always prints at least once, so no other arguments are needed. '
-v' captures the result in a variable instead of printing it directly.
Then a global replacement
parameter substitution is used to replace each zero with the desired string. The '
%b' format token in the second
printf expands backslash escapes like '
\n' in the input (making it equivalent to '
echo -en'), thus giving you a newline after each 'hi'.