3

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?

7
  • Do you want to pass testString as argument to shellscript1? Commented Nov 10, 2018 at 9:10
  • 1
    you could use putenv and call the script with that variable instead of $1 Commented Nov 10, 2018 at 9:13
  • 3
    you could just popen("bash") and feed it your bash commands. Commented Nov 10, 2018 at 9:14
  • 4
    This might help: C: Anyway to load parameters into a system() call or Passing variables to system function in C Commented Nov 10, 2018 at 9:15
  • 1
    don't bash your head anymore when you can feed it to a python :) Commented Nov 10, 2018 at 9:25

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for coding our comments into reality :) I'm running windows so I couldn't risk to post a non-working solution.
@Jean-FrançoisFabre Added a slightly more original solution so I'm not just copying the comments. :)
of course there was no snark in my answer as you probably understood, but I prefered to re-state it. Good answer
@PSkocik beautiful and elegant solution. Thank you, kind sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.