Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function from a shell-script from C

Tags:

c

bash

shell

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.

like image 728
Richard Avatar asked May 15 '26 21:05

Richard


2 Answers

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)

like image 165
Frxstrem Avatar answered May 18 '26 09:05

Frxstrem


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

like image 33
Olaf Dietsche Avatar answered May 18 '26 09:05

Olaf Dietsche