Home > Net >  Function Arguments in lists in loop (Bash)
Function Arguments in lists in loop (Bash)

Time:03-30

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 :)

CodePudding user response:

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.

CodePudding user response:

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
  • Related