3

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


2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0
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.

3 Comments

func a b c: bash: printf: a: invalid number.
HI John3136, thanks for your answer, sadly it doesn#t work with my code, I still get the error message: invalid number, for each passed parameter. I would have preferred your way, because of the easier readability of the loop arguments. Thank you
there was a typo - last %s in the print was a %d - may explain an invalid number...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.