1

I have a following code:

function test() {
    for ft in "$1"; do
        echo $ft
    done
}

test 5

I am trying to loop through number 12, therefore I want ft to be 1,2,3,4,5 respectively in each loop. But it is just printing 5. I also tried {1..$1} but result is still same. Please help!

Axel
  • 123

2 Answers2

2

I'm not totally sure what you're asking. Do you want to supply a parameter, and loop over the values from 1 to that value? If so, you can do this with bash (and probably other shells as well:

function test() {
    for ((i = 1; i <= $1; ++i)); do
        echo $i
    done
}

test 12
1
2
3
4
5
6
7
8
9
10
11
12

If you don't have a shell that supports the for(...) syntax, you can do the same thing with:

function test() {
    i=1

    while [ $i -le $1 ]; do
        echo $i
        i=$(expr $i + 1)
    done
}
Andy Dalton
  • 13,993
0

You can solve this in two ways:

  1. Give the function a single integer and let it output the integers between some start value (1) and that integer:

    count_up () { seq "$1"; }
    

    or

    count_up () {
        for (( i = 1; i <= $1; ++i )); do
            echo "$i"
        done
    }
    

    or

    count_up () {
        value=1
    
        while [ "$value" -le "$1" ]; do
            echo "$value"
        done
    }
    

    or any other number of variations.

  2. Give the actual integers as arguments to the function using e.g. count_up {1..5} and define the function as simply

    count_up () { printf '%s\n' "$@"; }
    

    or

    count_up () {
        for value do
            echo "$value"
        done
    }
    

    Although, there would not be much point in doing it this way as you could just call seq 5 or use printf '%s\n' {1..5} directly (also, the function should probably be called something like list_args instead).

Kusalananda
  • 333,661