0

I want to save the output from a bash script which is invoked from a C program to a variable declared in the C program. I searched and tried successfully calling a script using system, and I tried this, but it didn't work:

char* a;
system("a=`ls`");
printf("%s",a);
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Brotchu
  • 115
  • 1
  • 8
  • bash variables have utterly and absolutely NOTHING to do with any variables you defined in your C app. – Marc B Aug 17 '15 at 17:51
  • You're assigning to a shell variable with no relation to your C variable. You will need to create a pipe and set the child's STDOUT to be the writer end of that pipe. This means you won't be able to use `system` – ikegami Aug 17 '15 at 17:53
  • one way, though messy, is to '>' the script output to a file. then, after the script exits, the C program opens that file for input and reads in the output from the script. Something like: system("ls > /tmp/LS_Output"); FILE * pLSO = fopen( "LS_Output", "r"); – user3629249 Aug 17 '15 at 18:02

1 Answers1

1

Use popen() system call. You can pass the cmd as the parameter. You will get the command output as text when the function returns. Hope this helps.

  • An answer with the same content has already been given to this question earlier (see the answer on the top marked as accepted). – Gergely Bacso Aug 17 '15 at 19:00