我只是从我的 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/