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

5
  • stackoverflow.com/questions/3736210/… Commented May 9, 2017 at 6: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. Commented May 9, 2017 at 6: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. Commented May 9, 2017 at 6:41
  • 1
    I am sorry. Would this be more like what you are trying to do ? stackoverflow.com/questions/5237482/… Commented May 9, 2017 at 6:46
  • Why is this tagged python? Commented May 9, 2017 at 7:24

1 Answer 1

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

1 Comment

hey, it partially works for me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.