1

I am writing a program in C that bash code as well. I need to assign the value of a C variable to a bash variable. More specifically I need to assign the argument supplied to C program to bash variable inside same program.

int main( int argc, char **argv)
{
    printf(argv[1]);
    system("echo $1"); // Here I need to assign argv[1] to bash variable.
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • create a buffer, write the value into it `sprintf(buf, "echo %s",argv[1])` and use system() on the buffer – Tommylee2k Aug 19 '19 at 13:12
  • What "bash variable"? How are you going to pass that information from bash to your program? Through the command-line (`$ ./a.out 42 FOO`), maybe? – pmg Aug 19 '19 at 13:13
  • @Tommylee2k `sprintf` - that is how you create a vulnerability in your application. – Maxim Egorushkin Aug 19 '19 at 13:14
  • @MaximEgorushkin I think that's the least of his problems ;) – Tommylee2k Aug 19 '19 at 13:17
  • int execle(const char *path, const char *arg, ... /*, (char *) NULL, char * const envp[] */); – RaminNietzsche Aug 19 '19 at 13:20
  • You may prefer to use `unistd.h`'s `int execve(const char *filename, char *const argv[], char *const envp[]);` to run your command and pass it arguments. – Léa Gris Aug 19 '19 at 13:25
  • Are you attempting to set a variable by running `./myprogram value` from the shell? You're better off just doing `VARIABLE=vale` directly in the shell. How exactly do you intend to use the bash variable? Also, can you clarify what you mean when you say you're "writing a program in C that bash code as well"? – dbush Aug 19 '19 at 13:36
  • 2
    Possible duplicate of [Passing variable from c program to shell script as argument](https://stackoverflow.com/q/18179346/608639) – jww Aug 19 '19 at 13:53

1 Answers1

0

You may use the setenv to set an environment variable which is accessible by your script.

#include <stdlib.h>

int main(int argc, char **argv) {
    setenv("VAR", argv[1], 1);
    system("echo $VAR");
    return 0;
}
Mox
  • 2,355
  • 2
  • 26
  • 42
  • Thanks a lot, its solved my problem. – Salman Raza Aug 19 '19 at 13:51
  • Doesn't work for me in bash: $ `FOOVAR=3; echo $FOOVAR; echo -e '#include \nint main(void){setenv("FOOVAR", "42", 1);}' | gcc -std=c11 -pedantic -D_XOPEN_SOURCE=700 -x c -; ./a.out; echo $FOOVAR` outputs "3 3", not "3 42". – pmg Aug 19 '19 at 13:58
  • @pmg, you are using it in a wrong way, because your shell script and system() in c program are not in the same session, one can simply execute the shell script from the c program, the environment variable will then be made available to the script executed in the code. – Mox Aug 19 '19 at 14:11