JulianOliveira JulianOliveira - 6 months ago 19
Linux Question

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. The problem occurs when I use in my script code something like

[[ "$devname" == "bus/"* ]]&& continue;
, executing this command returns error, probably because when executing the sheel script the environment are in
dash
instead of
bash
. I tried to execute the command with
#!/usr/bin/env bash
but don't work. The full command is hardcoded inline and I'm avoiding the use of a shell script file.

Answer

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. In C++ you'll have to escape the inner quotes if you use the above literally, so:

const char* command = "bash -c '[[ \"$devname\" == \"bus/\"* ]] && hostname || echo \"no\"'";