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
  • 5
  • Duplicate of https://unix.stackexchange.com/questions/63931/how-to-iterate-through-a-comma-separated-list-and-execute-a-command-for-each-ent – steve Nov 30 '19 at 15:23
  • Looks more like [How to convert an input parameter to integer value in a for loop in bash?](https://unix.stackexchange.com/questions/418809/how-to-convert-an-input-parameter-to-integer-value-in-a-for-loop-in-bash) to me – steeldriver Nov 30 '19 at 15:26
  • Thanks @steeldriver! – Axel Nov 30 '19 at 15:31
  • You are only providing one argument to your function. Looping over that would just print `5` (not `12`). It's unclear what it is you are actually wanting to do. How is the sequence `1,2,3,4,5` related to `12`? – Kusalananda Nov 30 '19 at 16:14
  • @Kusalananda My bad. Actually it's 5 not 12. – Axel Dec 02 '19 at 10:02

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,654
  • 1
  • 25
  • 45
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
  • 320,670
  • 36
  • 633
  • 936