system("command") produces an error; but it works when invoked directly from Bash prompt
As mentioned system()
creates a new standard shell sh
and executes the commands. Since <()
is a bash specific feature it can't be interpreted by sh
.
You can circumvent this by calling bash
explicitly and use the -c
option:
system("bash -c \"diff <(cat /etc/passwd) <(ls -l /etc)\"");
or using a raw string literal:
system(R"cmd(bash -c "diff <(cat /etc/passwd) <(ls -l /etc)")cmd");
Here's the relevant part of the system(3)
call manual page:
The
system()
library function usesfork(2)
to create a child process that executes the shell command specified in command usingexecl(3)
as follows:
execl("/bin/sh", "sh", "-c", command, (char *) 0);
system()
returns after the command has been completed.
The system(3)
call invokes /bin/sh
to process the command. If you want specifically use bash
features, you need to insert bash -c
in front of the command string, which will run bash
and tell it to process the remainder of the string.
system("bash -c \"diff <(cat /etc/passwd) <(ls -l /etc)\"");