0

I want to call/execute a bash from a C program including any number of arguments passed on the command line for the script.

I found a related post How to pass command line arguments from C program to the bash script? but my case is the number of arguments pass to the command line may vary, it's not fixed number. So the C program has to collect any number of command line arguments and pass the same to the bash script to execute.

Is this possible?.

To give you a clear idea, when I run my test bash script, I get the output as expected.

# ./bashex.sh
No arguments passed

# ./bashex.sh hello world
Arguments passed are #1 = hello
Arguments passed are #2 = world

# ./bashex.sh hello world Hi
Arguments passed are #1 = hello
Arguments passed are #2 = world
Arguments passed are #3 = Hi

What I do not know is how to execute this script like this including the command line arguments from a C program

Community
  • 1
  • 1
vjwilson
  • 754
  • 2
  • 14
  • 30
  • http://stackoverflow.com/questions/3736210/how-to-execute-a-shell-script-from-c-in-linux – James Brown May 09 '17 at 06:22
  • Thank you, I have got some C programs already to execute another script on the server. The question is collect any number of arguments passed on the command line and pass the same to the bash script the C program executes. – vjwilson May 09 '17 at 06:25
  • @Badda no brother. As you can see that thread has only a portion of my question. The thread discuss only how to execute a shell script from C in Linux. My question is to execute a shell including the command-line arguments for the script. – vjwilson May 09 '17 at 06:41
  • 1
    I am sorry. Would this be more like what you are trying to do ? http://stackoverflow.com/questions/5237482/how-do-i-execute-external-program-within-c-code-in-linux-with-arguments – Badda May 09 '17 at 06:46
  • Why is this tagged python? – Ajay Brahmakshatriya May 09 '17 at 07:24

1 Answers1

0

Pretty much bare minimum, nothing checked, ./foo segfaults if no argument, use at own risk:

$ cat foo.c
#include<stdlib.h>
#include<string.h>

int main (int argc, char *argv[])
{
  char bar[100]="./bar.sh ";
  strcat(bar, argv[1]);
  system(bar);
}

The script:

$ cat bar.sh
#!/bin/sh
echo $1

The execution:

$ ./foo baz
baz
James Brown
  • 36,089
  • 7
  • 43
  • 59