Run C# Commands in Bash Terminal (Linux)

I felt excited when noticed I can run C# commands with mono csharp shell using Terminal in Linux.
Let's try it...

First of all, for Ubuntu, mono-csharp-shell package should be installed on your system.

To start C# shell:

$ csharp
csharp> using System.IO;
csharp> Directory.GetFiles("/etc");

We can also load a dll library and call a function in it:

csharp> LoadAssembly ("/media/data/lib/mbLib/bin/mbLib.dll");
mbLib.Dosya.Download( "", "/media/os/sil", "test.mp3");

We can also run C# code from file:

$ csharp /media/os/sil/test.csx

test.csx file content:

LoadAssembly ("/media/data/lib/mbLib/bin/mbLib.dll"); 
    var r = mbLib.Dosya.Download( "", "/media/os/sil", "test.mp3"); 
    Console.WriteLine("Download size: " + r);
}catch(Exception ex){

Note: .csx and .dll files in ~/.config/csharp folder, loaded at start. We can copy frequent used library or create startup scripts there.

Run C# Code Block and Return:

I spent a few hours to be able to pass a parameter from Terminal. But the help output not listed a parameter like this.
Finally, I thought I could play with source code. I download the source and opened it with MonoDevelop. When I examining it I noticed that, "-e" parameter (not listed in help output) already allow to run and exit.
I don't know why the developers not listing this -e parameter on help output. 
Then I tried man page. It was listed there. It's my mistake not to look at man page a few hours ago. So there is no reason anymore to edit the source for me. 

$ csharp -e 'Math.Pow(3,4);'
output: 81

Whe can also pass parameter from terminal and get result as bash variable:

$ a="   abc xyz 123       "
$ b=$(csharp -e "string s=\"$a\"; Console.Write(s.Trim());");
$ echo =$b=
output: =abc xyz 123=

Isn't it excited? :)

One more example... This shows how long will it take to run the command block:

$ csharp -e "Time (() => { string[] s = System.IO.Directory.GetFiles(\".\");  print(s.Length + \" files found in current dir.\"); foreach (string f in s) print(f); });"

Extended Samples: 

Read from XML Files and Insert into SQLite Database

The following code block demonstrating how to read data from multiple XML files and insert to SQLite database using Terminal.

$ for f in *.xml; do sql=$(csharp  -e 'var xdoc = new System.Xml.XmlDocument(); xdoc.Load('\"$f\"'); string word=xdoc.GetElementsByTagName("word").Item(0).InnerText; string definition=xdoc.GetElementsByTagName("definition").Item(0).InnerText; string sentence=xdoc.GetElementsByTagName("sentence").Item(0).InnerText; string s=string.Format("INSERT INTO wordmaster(word, definition, sentence, extra) VALUES (\"{0}\", \"{1}\",\"{2}\",\"{3}\") ", word, definition , sentence, '\"$f\"'); Console.Write(s);'); sqlite3 wm.sqlite "$sql"; sleep 0.1; done;


Share Share Editor: editor | Posted: 2015/01/28 | Views: 10847


13 + 5 =
Home | Search | Contact | Terms