Search code examples
arraysstringbashfor-loopecho

Parametrized population of a string in bash from 1 to n


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!


Solution

  • 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