0

I have written one bash script and now I am calling this script from C program. Now I want to pass arguments i.e. argv[1] and argv[2] to the script from command line.

1
  • 5
    You need to show some code. It depends on what you're using to invoke the script from the C program, but most likely it's something in the exec*() family of system calls. Those support passing command line arguments in quite a straightforward fashion. In fact you must pass command line arguments when using those system calls. Therefore I don't know where you're hitting some difficulty. Commented Dec 1, 2014 at 8:02

1 Answer 1

3

It depends on the way the script is called. For example, if you are using system you can preformat string that used to invoke bash script from system call adding command line arguments:

C

#include "stdio.h"

void main(int argc, char const *argv[])
{
    if (argc == 2) {
        char command[100] = {0};

        sprintf(command, "./example.sh %s", argv[1]);
        system(command);
    }
}

Bash

#!/bin/bash

echo $1

As a result

$ gcc example.c -o example && ./example Hello!
Hello!
Sign up to request clarification or add additional context in comments.

4 Comments

Using system() is insecure. What if argv[1] contains a space or a shell metacharacter?
It is just an example. It is up to author to implement additional security and reliability checks.
I don't agree. I believe it is up to us experts to recommend secure interfaces like fork()+execve() instead of system(). If we recommend system(), people are going to use it and write insecure code.
@Calada, can you answer whit a secure solution?

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.