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?
In the C programming standard library, there is a function named system () which is used to execute Linux as well as DOS commands in the C program.
An alternative to using system to execute a UNIX command in C is execlp. It all depends on the way you want to use them. If you want user input, then you might want to use execlp / execve. Otherwise, system is a fast, easy way to get UNIX working with your C program.
cc command is stands for C Compiler, usually an alias command to gcc or clang. As the name suggests, executing the cc command will usually call the gcc on Linux systems. It is used to compile the C language codes and create executables.
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'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With