Is this possible?
Here is an example:
#include <stdio.h>
#include <stdlib.h>
char testString[]="blunt"
#define shellscript1 "\
#/bin/bash \n\
printf \"\nHi! The passed value is: $1\n\" \n\
"
int main(){
system(shellscript1);
return 0;
}
Now I would like to pass a value from testString to shellscript1 without having to reserve to making a temporary external script.
I've been bashing my head, and I couldn't figure out how to do it. Does anyone have any ideas?
Using the environment is possibly the simplest way to achieve it.
#include <stdio.h>
#include <stdlib.h>
char testString[]="blunt";
#define shellscript1 "bash -c 'printf \"\nHi! The passed value is: $testString\n\"'"
int main()
{
if(0>setenv("testString",testString,1)) return EXIT_FAILURE;
if(0!=system(shellscript1)) return EXIT_FAILURE;
return 0;
}
There are other ways, like generating the system argument in a buffer (e.g., with sprintf) or not using system.
system treats its argument like a a string to come after "/bin/sh", "-c". In my answer to using system() with command line arguments in C I coded up a simple my_system alternative that takes the arguments as a string array.
With it, you can do:
#define shellscript1 "printf \"\nHi! The passed value is: $1\n\" \n"
char testString[]="blunt";
int main()
{
if(0!=my_system("bash", (char*[]){"bash", "-c", shellscript1, "--", testString,0})) return EXIT_FAILURE;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With