Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash for loop in function with passing parameters

i´m new to bash and couldn`t find any fitting answer, hopefully you guys can help me. Sorry if the answer to my question is too obvious.

I want to create a function with variable number of parameters, that should be printed out with a for loop. The parameters passed are the printable Strings. The output should be the number of the "for loop" starting with 1 and then the passed argument. I can´t find the solution to say: Print the number of the iteration, then print the function parameter at position of the iteration.

I always get the error: invalid number

Please excuse the confusion. THANKS

it should look like this

SOME TEXT

1: String1
2: String2
3: String3
func()  {
 echo -e "SOME TEXT"

        for i in "$@"; do
            printf  '%d: %s\n' "$i" "$@"   # I also tried "${i[@]}"
        done

}

func String1 String2 String3


like image 915
dagonsts Avatar asked Apr 19 '26 10:04

dagonsts


1 Answers

In your code, $i will be each argument passed to the function. That can't be converted to a number according to printf, so it complains. That is because $@ is a list of all the arguments passed to the function. In your case, $@ contains the elements String1, String2 and String3.

This is what you mean:

func(){
    echo -e "SOME TEXT"
    i=0
    for arg in "$@"; do
        i=$((i+1))
        printf '%d: %s\n' "$i" "$arg"
    done
}
func String1 String2 String3
like image 190
Quasímodo Avatar answered Apr 21 '26 23:04

Quasímodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!