How can I execute a shell script from C in Linux?
6 Answers
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
-
3It's also worth noting that fork() is quite cheap since the memory is copy-on-write and not duplicated as soon as the program forks. Commented Sep 17, 2010 at 15:33
-
1I'm a big fan of fork/exec - it lets you avoid environment-based uncertaintly about what's going to run. But can you use it on shell scripts directly? As you say, by using exec, you "avoid having the shell (/bin/sh) run your command for you"; don't you thus need to exec /bin/sh to run a shell script? Commented Sep 17, 2010 at 16:33
-
2@Tom Anderson: If the shell script has execution permissions set for the effective user and has an appropriate shabang first line listing a file which the effective user also has permission to execute and also is not itself a script of some sort then the kernel will call the file listed on the shabang line with the script file. If the script's shabang were
#!/bin/csh
then/bin/sh
would not be run in the fork/exec scenario. If it were#!/bin/sh
then it would in the fork/exec scenario, but with thesystem
version/bin/sh
would be run twice for this script. Commented Sep 17, 2010 at 16:43
You can use system
:
system("/usr/local/bin/foo.sh");
This will block while executing it using sh -c
, then return the status code.
-
3... assuming it has executable bit and shebang line. In general,
system("/bin/sh /usr/local/bin/foo.sh");
. Yes, this actually calls the shell twice. Commented Sep 17, 2010 at 15:07 -
Hi Matt. This is useful. But, I see it is blocking. How do I make it asynchronous?– mdasariCommented Aug 18, 2018 at 22:27
-
Even if the script is executable, system("script.sh") says "script.sh not found", even with absolute path. It works only with system("sh script.sh")– R71Commented Jun 24, 2022 at 15:37
If you're ok with POSIX, you can also use popen()
/pclose()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* ls -al | grep '^d' */
FILE *pp;
pp = popen("ls -al", "r");
if (pp != NULL) {
while (1) {
char *line;
char buf[1000];
line = fgets(buf, sizeof buf, pp);
if (line == NULL) break;
if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
}
pclose(pp);
}
return 0;
}
A simple way is.....
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate
and send to the system(concatenated_string); */
int main()
{
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT); //it will run the script inside the c code.
return 0;
}
Say thanks to
Yoda @http://www.unix.com/programming/216190-putting-bash-script-c-program.html
-
I actually like the clever idea of placing the script in a define, thanks for posting. Commented Jul 21, 2023 at 7:15
-
Doesn't work. Try this
sh #!/bin/bash exec 1> >(logger -s -t $(basename $0) 2>&1) exec 2> >(logger -s -t $(basename $0)) out=$(ls /Users/me/Library/Mail) osascript -e "display dialog \"$out\""
Commented Aug 7 at 1:06
If you need more fine-grade control, you can also go the fork
pipe
exec
route. This will allow your application to retrieve the data outputted from the shell script.
I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.
Store you command in a char array parameters, and malloc space for the result.
int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
fprintf(stderr, "FORK failed");
return 1;
} else if( childpid == 0) {
close(1);
dup2(fd[1], 1);
close(fd[0]);
execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);
-
close(1);
is not needed as dup2() closes the newfd by itself before re-assigns it.– FedCommented Jun 9, 2017 at 23:11