I wanted a character to be repeated n times based on a variable or function and I ended up using the seq command but that's only because I don't understand how to use brace expansions with variables or functions. {1..$num} or {1..$(num)}
#function w/ seq
num() { echo $(shuf -i 0-50 -n 1); }
repeat() { for i in $(seq 1 $(num));do echo -n "$1";done; }
repeat -
if you modify the above function to a variable that works as well.
#variable w/ seq
num=$(echo $(shuf -i 0-50 -n 1))
repeat() { for i in $(seq 1 $num);do echo -n "$1";done; }
repeat -
My question is, how can I use brace expansions to get the same results using a variable or function?
what I tried didn't work...
#function with brace expansion
num() { echo $(shuf -i 0-50 -n 1); }
repeat() { for i in {1..$(num)};do echo -n "$1";done; }
repeat -
and as a variable...
#variable with brace expansion
num=$(echo $(shuf -i 0-50 -n 1))
repeat() { for i in {1..$num};do echo -n "$1";done; }
repeat -
The output is just the one character that resides at $1 when repeat is called... regardless of the range of $num or $(num) being 0-50, I know I'll get a 0 or 1 at some point...
It'll function but only if I replace $num or $(num) with a fixed number. Doesn't seem to work with a variable or function in place.
Also am I using these brace expansions correctly when I think of them as a range or a bit like seq or a sequence? thanks
EDIT
short answer you can't use variables with brace expansions in bash without the use of some trickery
looks like the best option is to use seq, C-style loop or use zsh
#C-style
num() { "5"; }
for((i=1; i<=$(num); i++)); do (num);done
or
num=5
for((i=1; i<=num; i++)); do echo "$num";done