Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Bash Commands from Mono C#

I am trying to make a directory using this code to see if the code is executing but for some reason it executes with no error but the directory is never made. Is there and error in my code somewhere?

var startInfo = new 

var startinfo = new ProcessStartInfo();
startinfo.WorkingDirectory = "/home";

proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();

Console.WriteLine ("Shell has been executed!");
Console.ReadLine();
like image 494
Brandon Williams Avatar asked Apr 12 '14 10:04

Brandon Williams


3 Answers

This works best for me because now I do not have to worry about escaping quotes etc...

using System;
using System.Diagnostics;

class HelloWorld
{
    static void Main()
    {
        // lets say we want to run this command:    
        //  t=$(echo 'this is a test'); echo "$t" | grep -o 'is a'
        var output = ExecuteBashCommand("t=$(echo 'this is a test'); echo \"$t\" | grep -o 'is a'");

        // output the result
        Console.WriteLine(output);
    }

    static string ExecuteBashCommand(string command)
    {
        // according to: https://stackoverflow.com/a/15262019/637142
        // thans to this we will pass everything as one command
        command = command.Replace("\"","\"\"");

        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = "-c \""+ command + "\"",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        proc.Start();
        proc.WaitForExit();

        return proc.StandardOutput.ReadToEnd();
    }
}
like image 60
Tono Nam Avatar answered Oct 08 '22 08:10

Tono Nam


This works for me:

Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
like image 43
Alex Erygin Avatar answered Oct 08 '22 07:10

Alex Erygin


My guess is that your working directory is not where you expect it to be.

See here for more information on the working directory of Process.Start()

also your command seems wrong, use && to execute multiple commands:

  proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";

Thirdly you are setting your working directory wrongly:

 proc.StartInfo.WorkingDirectory = "/home";
like image 36
thumbmunkeys Avatar answered Oct 08 '22 08:10

thumbmunkeys