[英]Forcing the environment to bash when executing shell command in C++
I'm creating an application in C++ that can execute some commands shell to get informations about the system. 我正在用C ++创建一个应用程序,该应用程序可以执行一些命令外壳来获取有关系统的信息。 The problem occurs when I use in my script code something like
[[ "$devname" == "bus/"* ]]&& continue;
当我在脚本代码中使用类似
[[ "$devname" == "bus/"* ]]&& continue;
的问题时,会发生问题[[ "$devname" == "bus/"* ]]&& continue;
, executing this command returns error, probably because when executing the sheel script the environment are in dash
instead of bash
. ,执行此命令将返回错误,这可能是因为在执行Sheel脚本时,环境为
dash
而不是bash
。 I tried to execute the command with #!/usr/bin/env bash
but don't work. 我试图用
#!/usr/bin/env bash
执行命令,但是不起作用。 The full command is hardcoded inline and I'm avoiding the use of a shell script file. 完整命令是内联的硬编码,我避免使用Shell脚本文件。
You have two options: 您有两种选择:
1) Explicitly set SHELL
via putenv()
: 1)通过
putenv()
显式设置SHELL
:
putenv("SHELL=/bin/bash");
execl(...);
2) Explicitly execute /bin/bash
, instead of relying on the hashbang: 2)显式执行
/bin/bash
,而不是依赖hashbang:
execl("/bin/bash", script.c_str(), NULL);
// script is the script you're trying to execute.
If you have a command like this, say: 如果您有这样的命令,请说:
[[ "$devname" == "bus/"* ]] && hostname || echo "no"
You can run it this way: 您可以通过以下方式运行它:
bash -c '[[ "$devname" == "bus/"* ]] && hostname || echo "no"'
So if you just build one string that contains the above, you can run it using popen()
or whatever. 因此,如果仅构建一个包含以上内容的字符串,则可以使用
popen()
或其他任何方式运行它。 In C++ you'll have to escape the inner quotes if you use the above literally, so: 在C ++中,如果直接使用上述内容,则必须转义内部引号,因此:
const char* command = "bash -c '[[ \"$devname\" == \"bus/\"* ]] && hostname || echo \"no\"'";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.