首页 > 解决方案 > 通过 C++ 程序将命令传递到 shell 脚本

问题描述

我正在尝试通过 C++ 程序将命令传递到我的 shell 脚本中,但我根本不熟悉 C++,虽然我知道我必须使用 system(),但我不确定如何有效地设置它。

#include <iostream>
#include <stdlib.h>

int main() {
        system("./script $1");

        return 0;

}

这是我目前拥有的。

似乎我不能在系统命令中使用位置参数,但我不确定还能做什么。我正在尝试通过 C++ 程序将参数传递给脚本。

标签: c++bashshellmakefile

解决方案


如果您只想调用“./script”,并将 C++ 程序的第一个参数作为脚本的第一个参数传递,您可以这样做:

#include <iostream>
#include <string>
#include <stdlib.h>

int main(int argc, char ** argv)
{  
   if (argc < 2)
   {  
      printf("Usage:  ./MyProgram the_argument\n");
      exit(10);
   }

   std::string commandLine = "./script ";
   commandLine += argv[1];

   std::cout << "Executing command: " << commandLine << std::endl;
   system(commandLine.c_str());
   return 0;
}

推荐阅读