I have a user supplied script like
#!/bin/sh
some_function () {
touch some_file
}
some_other_function () {
touch some_other_file
}
and i want to call the function some_other_function from c-code.
I understand, that i could simply write a shell script like
#!/bin/sh
source userscript.sh
some_other_function
and execute it using system(), but i am looking for a more elegant and especially a more generic solution, that lets me execute arbitrarily named functions and maybe even lets me get/set variables.
You cannot do this directly from C. However, you can use system to run a command (like sh) from C:
// Run the command: sh -c 'source userscript.sh; some_other_function'
system("sh -c 'source userscript.sh; some_other_function'");
(Note that the sh -c 'command' lets you run command in a shell.)
Alternatively, you can also use execlp or some other function from the exec family:
// Run the command: sh -c 'source userscript.sh; some_other_function'
execlp("sh", "sh", "-c", "source userscript.sh; some_other_function", NULL);
(Note here that when using exec functions, the first argument – "sh" – must be repeated)
From the comments, I understand that you want to call one of several functions defined in your script. You can do this, if you give the function as an argument to the shell script and in the last line just have $1, e.g.
fun1()
{
echo "fun1 called"
}
fun2()
{
echo "fun2 called"
}
$1
You can then call your script as
sh userscript.sh fun1
which gives
fun1 called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With