繁体   English   中英

将值从C变量传递给嵌入式shell脚本?

[英]Pass a value from a C variable to an embedded shell script?

这可能吗?

这是一个例子:

#include <stdio.h>
#include <stdlib.h>

char testString[]="blunt"

#define shellscript1 "\
#/bin/bash \n\
printf \"\nHi! The passed value is: $1\n\" \n\
"

int main(){

    system(shellscript1);

    return 0;
}

现在我想将testString的值传递给shellscript1而不必保留创建临时外部脚本。

我一直在抨击我,我无法弄清楚如何去做。 有没有人有任何想法?

使用环境可能是实现它的最简单方法。

#include <stdio.h>
#include <stdlib.h>

char testString[]="blunt";
#define shellscript1 "bash -c 'printf \"\nHi! The passed value is: $testString\n\"'"
int main()
{
    if(0>setenv("testString",testString,1)) return EXIT_FAILURE;
    if(0!=system(shellscript1)) return EXIT_FAILURE;
    return 0;
}

还有其他方法,比如在缓冲区中生成system参数(例如,使用sprintf )或不使用system

system将其参数视为字符串,以"/bin/sh", "-c" 使用带有C语言命令行参数的system()的 答案中 ,我编写了一个简单的my_system替代方法,它将参数作为字符串数组。

有了它,你可以做到:

#define shellscript1 "printf \"\nHi! The passed value is: $1\n\" \n"
char testString[]="blunt";
int main()
{
    if(0!=my_system("bash", (char*[]){"bash", "-c", shellscript1, "--", testString,0})) return EXIT_FAILURE;
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM