我正在从“c”程序调用 shell 脚本,并且在 c 中有一些变量,我想将它们作为参数传递给 shell 脚本。我尝试使用 system() 调用 shell 脚本,但我作为参数传递的变量被视为字符串而不是变量。
最佳答案
shell 脚本(a.sh):
# iterates over argument list and prints
for (( i=1;$i<=$#;i=$i+1 ))
do
echo ${!i}
done
C 代码:
#include <stdio.h>
int main() {
char arr[] = {'a', 'b', 'c', 'd', 'e'};
char cmd[1024] = {0}; // change this for more length
char *base = "bash a.sh "; // note trailine ' ' (space)
sprintf(cmd, "%s", base);
int i;
for (i=0;i<sizeof(arr)/sizeof(arr[0]);i++) {
sprintf(cmd, "%s%c ", cmd, arr[i]);
}
system(cmd);
}
关于c - 将变量从c程序作为参数传递给shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18179346/