2

Will I execute shell script .sh if I run code like this:

int system (char *s);
int sh_exec_ok; //Shell script execution flag

sh_exec_ok = system("something/script_name.sh");

What do you suggest me to use to execute shell scripts in C code?

  • `system()` should do it finely ;) In fact, it executes a `command line` as if you were in a shell, so that's ok. (For example you can run a `ls` with `system()` – Guillaume Munsch Jun 29 '15 at 08:12
  • 2
    I'd suggest you _don't_ execute shell scripts in C like that, but if your path is correct, and your script is ok, then your code _should_ work... just try it and see – Elias Van Ootegem Jun 29 '15 at 08:13
  • `system()` can execute any shell command if it's path is correct. Donot forget to include `stdlib.h`. However, it is not recommended as it makes the code platform dependent. – Shreevardhan Jun 29 '15 at 08:28
  • @Shreevardhan i run it on Debian, and I think it will work –  Jun 29 '15 at 08:35
  • possible duplicate of [How to execute a shell script from C in Linux?](http://stackoverflow.com/questions/3736210/how-to-execute-a-shell-script-from-c-in-linux) – Raman Jun 29 '15 at 09:50

1 Answers1

2

Using system is the right way to run a shell command. Some notes:

  • You should not declare system yourself. Instead, do #include <stdlib.h>
  • If portability is a concern, do system(NULL). If the return value is non-zero, then a command processor to handle the system function call is available.
  • It is good practice to use the full path to the shell script, or set the path so it executes the version of the shell script you want to execute.
Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46