'Function Arguments in lists in loop (Bash)
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 :)
Solution 1:[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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Antonio Petricca |
| Solution 2 | Aurèle Petit |
