I have
#!/bin/sh
func1()
{
echo "This is func1 from shell script"
}
func2()
{
echo "This is func2 from shell script"
}
I want to call func1 and func2 from a C program. Can I do that ?
This is unlikely to be a good idea, but I suppose you could write something like this:
if (! fork()) { // TODO fork can return -1 on error; should check for that
execl("/bin/sh", "-c", ". FILE && func1", (char *)NULL);
// TODO should check to make sure execlp successfully replaced the process
}
where FILE is the name of the .sh file that defines func1. The above will spawn a child process, and replace that child process with an instance of Bash (or whatever your shell is) with the arguments -c (meaning "the script to run is the next argument") and . FILE && func1 (which is the script; it means "run the commands in FILE, and if that succeeds, then run the command func1").
For more information:
; is just a way of separating commands. You can use \n instead if you prefer. (The two are not completely equivalent in all cases, but they're equivalent in most cases.)&& instead of ;A little simpler than using fork / exec is the stdlib "system" command.
See man 3 system.
Assume your bash functions are in file "/tmp/scripts.sh" ...
system("bash -c \". /tmp/scripts.sh ; func1 ; func2\"");
.sos, and load them into bash with theenablebuiltin.