Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run shell script with C# on OSX?

Tags:

c#

macos

unity3d

I'd like to use C# to execute a shell script. Based on similar questions I came to a solution that looks like this.

System.Diagnostics.Process.Start("/Applications/Utilities/Terminal.app","sunflow/sunflow.sh");

It currently opens Terminal, then opens the shell file with the default application (Xcode in my case). Changing the default application is not an option, since this app will need to be installed for other users.

Ideally the solution will allow for arguments for the shell file.

like image 618
miketucker Avatar asked Sep 06 '12 15:09

miketucker


People also ask

Are shell scripts written in C?

C shell's scripting syntax is modeled after the C language in some aspects. Small programs can be created by writing scripts using the C shell syntax.

What is the use of C in shell script?

The C shell allows you to assign aliases and use them as you would commands. The shell maintains a list of the aliases that you define. The C shell maintains a set of variables, each of which has as its value a list of zero or more words. Some of these variables are set by the shell or referred to by it.

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.


1 Answers

I can't test with a Mac right now, but the following code works on Linux and should work on a Mac because Mono hews pretty closely to Microsoft's core .NET interfaces:

ProcessStartInfo startInfo = new ProcessStartInfo()
{
    FileName = "foo/bar.sh",
    Arguments = "arg1 arg2 arg3",
};
Process proc = new Process()
{
    StartInfo = startInfo,
};
proc.Start();

A few notes about my environment:

  • I created a test directory specifically to double-check this code.
  • I created a file bar.sh in subdirectory foo, with the following code:

    #!/bin/sh
    for arg in $*
    do
        echo $arg
    done
    
  • I wrapped a Main method around the C# code above in Test.cs, and compiled with dmcs Test.cs, and executed with mono Test.exe.

  • The final output is "arg1 arg2 arg3", with the three tokens separated by newlines
like image 150
Adam Mihalcin Avatar answered Oct 06 '22 12:10

Adam Mihalcin