c++ - 将命令行参数传递给从 C++ 程序调用的 bash shell 脚本

标签 c++ bash shell unix

我只是从我的 C++ 程序中调用 shell 脚本。 Shell 脚本正在成功执行。但是我无法接收通过 C++ 程序传递给 shell 脚本的命令行参数。

#include<iostream>


    int main()
    {
       system(". script.sh a b v d d");


       return 0;
    }

shell

echo "start | $2 | $1 | $3"

O/P:

./a.out
start |  |  |

最佳答案

当您想将 shell 脚本的内容加载到当前 shell 中时,将应用您使用的语法。这意味着,加载变量定义、函数等。

system(". script.sh a b v d d");
        ^^^^^^^^^^^

等同于运行:

system("source script.sh a b v d d");
        ^^^^^^^^^^^^^^^^

您应该使用以下语法之一调用脚本:

system("./script.sh a b v d d");
system("bash script.sh a b v d d");

因此,当您执行您的程序时,唯一发生的事情就是您的脚本被源代码。没有向其中传递任何参数。这为您提供了在没有任何输入参数的情况下运行 echo "start | $2 | $1 | $3" 的输出。

关于c++ - 将命令行参数传递给从 C++ 程序调用的 bash shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33798988/

相关文章:

c++ - 重载 [] 时读取并插入 vector

c++ - 体系结构 x86_64 : Building a Stack 的 undefined symbol

linux - 应用程序在 bash 脚本中运行时找不到字符设备文件

bash - 提取子字符串直到第一个数字

c++ - 这种引用的使用不正确吗?

c++ - 尝试在 C++11 线程中使用已删除的函数

bash - 提取括号之间的字符串

Bash shell 脚本 - 设置变量时出错

python - 识别多个文件中的公共(public)元素

linux - Bash 字符串参数空格截断