dagonsts
dagonsts

Reputation: 43

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


Upvotes: 3

Views: 1685

Answers (2)

John3136
John3136

Reputation: 29265

func() {
    echo -e "SOME TEXT"
    for ((i=1; i<=$#; i++)); do
        eval str=\$$i
        printf '%d: %s %s\n' "$i" "$str" "${!i}"
    done
}

Uses indirect references to access the variable. str is the old way, ${!i} is a newer shorthand approach.

Upvotes: 0

Quas&#237;modo
Quas&#237;modo

Reputation: 4004

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

Upvotes: 5

Related Questions