0

i encountered a problem in my script. I don't know how to call a "Function with Argument" in a "List" in a "Loop".

Here is my code :

    f_test1()
    {
        echo "This is test 1"
    }
    
    f_test2()
    {
        echo "Is this test2 ? $1"
    }
    
    functions_list=("f_test1" "f_test2 \"yes\"")
    
    IFS=""
    for function in ${functions_list[*]}; do
        ${function[@]}
    done

and the output :

    This is test 1
    test.sh: line 15: f_test2 "yes": command not found

Why f_test1 works while f_test2 with the argument yes doesn't ?

Thanks for help :)

2 Answers 2

1

Rewrite your script as follow:

#!/bin/bash

f_test1()
{
    echo "This is test 1"
}

f_test2()
{
    echo "Is this test2 ? $1"
}

functions_list=("f_test1" "f_test2 yes")

IFS=""
for function in ${functions_list[*]}; do
    eval ${function[@]}
done

Now the output is:

This is test 1
Is this test2 ? yes

PS: I removed brackets around yes (not strictly required, only for readability) and added eval to invoke the method.

Sign up to request clarification or add additional context in comments.

1 Comment

What exactly is the point in writing ${function[@]}? The variable function is not an array, and you could equally well write just $function. And, shouldn't it be quoted, i.e. eval "$function"?
0

Here is (another) solution ...

f_test1()
{
    echo "This is test1"
}

f_test2()
{
    echo "Is this test2 ? $1"
}

functions_list=("f_test1" "f_test2 \"yes\"")

for function in "${functions_list[@]}"; do
    $function
done

Comments

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.