How to run a bash script from C++ program
Since this is a pretty old question, and this method hasn't been added (aside from the system()
call function) I guess it would be useful to include creating the shell script with the C binary itself. The shell code will be housed inside the file.c
source file. Here is an example of code:
#include <stdio.h>#include <stdlib.h>#define SHELLSCRIPT "\#/bin/bash \n\echo -e \"\" \n\echo -e \"This is a test shell script inside C code!!\" \n\read -p \"press <enter> to continue\" \n\clear\"int main() {system(SHELLSCRIPT);return 0;}
Basically, in a nutshell (pun intended), we are defining the script name, fleshing out the script, enclosing them in double quotes (while inserting proper escapes to ignore double quotes in the shell code), and then calling that script's name, which in this example is SHELLSCRIPT
using the system()
function in main()
.