8

I am using the following code to run a Linux console command via Mono in a C# application:

ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c ls");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

String result = proc.StandardOutput.ReadToEnd();

This works as expected. But, if i give the command as "-c ls -l" or "-c ls /path" I still get the output with the -l and path ignored.

What syntax should I use in using multiple switches for a command?

4
  • 2
    You could try using ProcessStartInfo.Arguments to see if the alternative method works? Also do you need the /bin/bash? can you not just run 'ls' direct? Commented Jul 23, 2014 at 12:49
  • @cjb110 no it doesn't work. Yes you do have to set /bin/bash as the filename or it cannot find the bash executable on its own. Commented Jul 23, 2014 at 13:04
  • Maybe try RedirectStandardInput and send the commands. I don't know the exact code but I do know you can do this to send input to the process. Here is a sample: msdn.microsoft.com/en-us/library/… Commented Jul 23, 2014 at 13:27
  • 1
    Is there a solution to this problem? I am having the same one. Commented Jul 28, 2014 at 23:28

1 Answer 1

3

You forgot to quote the command.

Did you try the following on the bash prompt ?

bash -c ls -l

I strongly suggest to read the man bash. And also the getopt manual as it's what bash use to parse its parameters.

It has exactly the same behavior as bash -c ls Why? Because you have to tell bash that ls -l is the full argument of -c, otherwise -l is treated like an argument of bash. Either bash -c 'ls -l' or bash -c "ls -l" will do what you expect. You have to add quotes like this:

ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c 'ls -l'");
Sign up to request clarification or add additional context in comments.

1 Comment

bash -c 'ls -l' is almost the same as bash -c "ls -l" but doesn't require escaping in C# string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.