python - C 程序执行 bash 脚本 + 传递其命令行参数

标签 python c linux bash shell

<分区>

我想从 C 程序调用/执行 bash,包括在脚本的命令行上传递的任意数量的参数。

我找到了相关帖子 How to pass command line arguments from C program to the bash script?但我的情况是传递给命令行的参数数量可能会有所不同,它不是固定数量。因此 C 程序必须收集任意数量的命令行参数并将其传递给 bash 脚本以执行。

这可能吗?

为了让您清楚地了解,当我运行我的测试 bash 脚本时,我得到了预期的输出。

# ./bashex.sh
No arguments passed

# ./bashex.sh hello world
Arguments passed are #1 = hello
Arguments passed are #2 = world

# ./bashex.sh hello world Hi
Arguments passed are #1 = hello
Arguments passed are #2 = world
Arguments passed are #3 = Hi

我不知道如何执行这个脚本,包括来自 C 程序的命令行参数

最佳答案

几乎是最低限度,没有检查,./foo 段错误如果没有参数,使用风险自负:

$ cat foo.c
#include<stdlib.h>
#include<string.h>

int main (int argc, char *argv[])
{
  char bar[100]="./bar.sh ";
  strcat(bar, argv[1]);
  system(bar);
}

脚本:

$ cat bar.sh
#!/bin/sh
echo $1

执行:

$ ./foo baz
baz

关于python - C 程序执行 bash 脚本 + 传递其命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862464/

相关文章:

c - 使用 fork() 计算接收到的命令行参数的总和时出现问题

c - 二进制 % 的无效操作数(有 .char*. 和 .int.)

java - 一些通过 Java 运行的终端命令在 Linux 中不显示输出

linux - 为什么循环会死掉?

python - Matplotlib Finance (mplfinance) 使用 mpf.plot() 格式化图表轴

Python安装setuptools,ez_setup.py报错

android - kivy android 分享图片

python - 尝试从Python3中的C函数获取数组

c - 如何设置相机的fps?

java - JDBC mysql 连接在 Win8 上比 Ubuntu14 慢得多