Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Linux Console Command in C#

Tags:

c#

mono

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?

like image 596
ravindu1024 Avatar asked Jul 23 '14 12:07

ravindu1024


People also ask

Can you use Linux commands in C?

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.

How do you call a UNIX command in C?

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.

What is Linux command C?

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.


1 Answers

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'");
like image 188
Fab Avatar answered Oct 08 '22 15:10

Fab