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.

Stanislav
  • 75
  • 4
subbarao
  • 107
  • 1
  • 3
  • 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. – Celada Dec 01 '14 at 08:02

1 Answers1

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!
Stanislav
  • 75
  • 4
  • Using `system()` is insecure. What if `argv[1]` contains a space or a shell metacharacter? – Celada Dec 03 '14 at 06:17
  • It is just an example. It is up to author to implement additional security and reliability checks. – Stanislav Dec 03 '14 at 09:59
  • 2
    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. – Celada Dec 03 '14 at 13:34
  • @Calada, can you answer whit a secure solution? – mox Jul 23 '19 at 06:43