简体   繁体   中英

Executed piped commands via System.Diagnostics.Process on Mono

Is it possible to execute the following piped commands via System.Diagnostics.Process ?

echo "test" | sudo -S shutdown -r +1

I've tried setting the file name to "/bin/bash", with the above as arguments, with no success.

...
var processStartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = "echo \"test\" | sudo -S shutdown -r +1" };
process.StartInfo = processStartInfo;
...

bash is interpreting your command as a file name followed by arguments, meaning it invokes echo and passes all the rest (including the pipe | ) to it for printing so you will get test | sudo -S shutdown -r +1 test | sudo -S shutdown -r +1 echoed and sudo won't be executed.

You should use the -c option to execute a command. Furthermore, you should quote the command itself so that it gets passed as a single argument. Something like this should work:

var processStartInfo = new ProcessStartInfo
{
    FileName = "/bin/bash",
    Arguments = "-c \"echo test | sudo -S shutdown -r +1\""
};

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