【问题标题】:Pass a value from a C variable to an embedded shell script?将值从 C 变量传递到嵌入式 shell 脚本?
【发布时间】:2019-04-13 17:13:27
【问题描述】:

这可能吗?

这是一个例子:

#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,而不必保留制作一个临时的外部脚本。

我一直在抨击我的头,但我不知道该怎么做。有人有什么想法吗?

【问题讨论】:

标签: c bash arguments


【解决方案1】:

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

#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" 之后的字符串。在my answerusing system() with command line arguments in C 中,我编写了一个简单的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;
}

【讨论】:

  • 感谢您将我们的 cmets 编码为现实 :) 我正在运行 Windows,所以我不能冒险发布无效的解决方案。
  • @Jean-FrançoisFabre 添加了一个稍微更原始的解决方案,所以我不只是复制 cmets。 :)
  • 当然,正如您可能理解的那样,我的回答中没有任何问题,但我更愿意重新陈述它。好答案
  • @PSkocik 美丽优雅的解决方案。谢谢你,好心的先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 2015-05-01
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多