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 Answer
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!
4 Comments
Celada
Using
system() is insecure. What if argv[1] contains a space or a shell metacharacter?Stanislav
It is just an example. It is up to author to implement additional security and reliability checks.
Celada
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.mox
@Calada, can you answer whit a secure solution?
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.