Home > Software engineering >  Parametrized population of a string in bash from 1 to n
Parametrized population of a string in bash from 1 to n

Time:03-31

Is there an easy way to populate a dynamic string with a size parameter?

lets say, we have:

Case N=1:
echo "Benchmark,Time_Run1" > $LOGDIR/$FILENAME

however, the run variable is parametric and we want to have all Time_Runs from 1 to n:

Case N=4:
echo "Benchmark,Time_Run1,Time_Run2,Time_Run3,Time_Run4" > $LOGDIR/$FILENAME

and the generic solution should be this form:

Case N=n:
echo "Benchmark,Time_Run1,...,Time_Run${n}" > $LOGDIR/$FILENAME

Is there a way to do that in a single loop rather than having two loops, one looping over n to generate the Run${n} and the other, looping n times to append "Time_Run" to the list (similar to Python)? Thanks!

CodePudding user response:

Use a loop from 1 to $n.

{
printf 'Benchmark'
for ((i = 1; i <= $n; i  )); do
    printf ',Time_Run%d' $i
done
printf '\n'
} > $LOGDIR/$FILENAME

CodePudding user response:

One way to populate the output string with a single loop is:

outstr=Benchmark
for ((i=1; i<=n; i  )); do
    outstr =",Time_Run$i"
done

It can also be done without a loop:

eval "printf -v outstr ',%s' Time_Run{1..$n}"
outstr="Benchmark${outstr}"

However, eval is dangerous and should be used only in cases where there is no reasonable alternative. This is not such a case. See Why should eval be avoided in Bash, and what should I use instead?.

  • Related