C++ system() API执行命令报错:sh: 1: Syntax error: "(" unexpected
Hey there, let's break down why you're hitting that sh: 1: Syntax error: "(" unexpected error and how to fix it directly without workarounds.
The Root Cause
The system() function in C++ defaults to calling /bin/sh instead of your regular interactive bash shell. On Ubuntu, /bin/sh is actually symlinked to dash—a lightweight POSIX-compliant shell that doesn't support bash-specific features like process substitution (<()). That's why the command works perfectly in your terminal (which uses bash) but fails when run via system().
The Direct Fix: Force system() to Use Bash
To make your command run correctly, you need to explicitly tell system() to execute the command with bash instead of sh. Wrap your entire command in bash -c "...", making sure to handle string escaping properly in C++.
Working C++ Code Example
Here's a clean implementation using C++11 raw string literals (avoids messy escape characters):
#include <cstdlib> #include <iostream> int main() { // Raw string literal lets us write the command without escaping quotes const char* cmd = R"(bash -c "comm -23 <(apt-mark showmanual | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)")"; int exit_code = system(cmd); if (exit_code != 0) { std::cerr << "Command failed with exit code: " << exit_code << std::endl; } return 0; }
If you're stuck with an older C++ standard that doesn't support raw strings, you can manually escape the double quotes:
const char* cmd = "bash -c \"comm -23 <(apt-mark showmanual | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)\"";
Quick Notes
- Why does this work in the terminal? Ubuntu's default interactive shell is bash, which supports process substitution.
system()uses the non-interactivesh(dash) by default, hence the mismatch. - If you wanted to avoid relying on bash entirely, you could rewrite the command using temporary files instead of
<(), but that would add unnecessary complexity. Using bash directly is the simplest and most direct fix here.
内容的提问来源于stack exchange,提问作者Ashutosh Pandey

