Home > Enterprise >  I get a can't execute binary file error when running a bash command from C#
I get a can't execute binary file error when running a bash command from C#

Time:06-26

I've created a Discord Bot with which you can interact (running on a Raspberry Pi with a default Raspberry Pi OS). I also added a command to execute a shell command. My code:

        ProcessStartInfo inf = new()
        {
              CreateNoWindow = true,
              RedirectStandardError = true,
              RedirectStandardOutput = true,
              RedirectStandardInput = true,
              FileName = "/bin/bash",
              Arguments = command,
        };
        if (Process.Start(inf) is Process cmd)
        {
                string ret = "Output: "   await cmd.StandardOutput.ReadToEndAsync();
                ret  = "\nError Output: "   await cmd.StandardError.ReadToEndAsync();
                await Program.Log(ret);
                return ret;
        }

When I set command to "echo Hello, World!" I just get the error

/usr/bin/echo: /usr/bin/echo: cannot execute binary file

from the StandardOutput. What am I doing wrong?

CodePudding user response:

You have to pass -c parameter to bash if you want execute something through it

ProcessStartInfo inf = new()
{
   CreateNoWindow = true,
   RedirectStandardError = true,
   RedirectStandardOutput = true,
   RedirectStandardInput = true,
   FileName = "/bin/bash",
   Arguments = $"-c \"{command}\""
};
if (Process.Start(inf) is Process cmd)
{
   string ret = "Output: "   await cmd.StandardOutput.ReadToEndAsync();
   ret  = "\nError Output: "   await cmd.StandardError.ReadToEndAsync();
   await Program.Log(ret);
   return ret;
}
  • Related