简体   繁体   中英

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.

You have two options:

1) Explicitly set SHELL via putenv() :

putenv("SHELL=/bin/bash");
execl(...);

2) Explicitly execute /bin/bash , instead of relying on the 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. 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\"'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM