csexec
is command-line tool to run C# source files as scripts in Linux environments using Mono framework.
It is evolved from the original idea described here on StackOverflow.
Major csexec
features comparing to the Mono C# REPL (csharp
):
- Full C# language features at your fingers!
- Ability to run script in a terminal emulator.
- Ability to pass command-line arguments to the script (csharp also supports this since Mono 5.0.0).
- Script source file name is available as a first argument.
The csexec is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
- Make
csexec
executable and copy it to the/usr/bin
:
chmod +x csexec
sudo cp -f csexec /usr/bin
- Add
#!/usr/bin/csexec
line at the beginning of C# source file. - Make C# source file executable.
- Optionally, change C# source file extension to something like
.csx
.
Note what csexec
writes compiler messages to csexec.log
file in its current working directory,
which may be not the same as a script source directory!
#!/usr/bin/csexec
using System;
public class Program
{
public static void Main (string [] args)
{
Console.WriteLine ("Hello, world!");
Console.WriteLine ("Arguments: " + string.Join (", ", args));
}
}
Use -t
switch to run script in terminal emulator window.
Consider add Console.ReadKey ()
to the end of the program
to pause script before it quits.
#!/usr/bin/csexec -t
using System;
public class Program
{
public static void Main (string [] args)
{
Console.WriteLine ("Hello, world!");
Console.WriteLine ("Arguments: " + string.Join (", ", args));
Console.Write ("Press any key to quit...");
Console.ReadKey (true);
}
}
Use -r:
compiler option to reference GAC assemblies:
#!/usr/bin/csexec -r:System.Windows.Forms.dll -r:System.Drawing.dll
using System;
using System.Drawing;
using System.Windows.Forms;
public class Program
{
public static void Main (string [] args)
{
MessageBox.Show ("Hello, world!");
}
}
csexec
allow reference file assemblies from the ~/.config/csharp
directory (same as with Mono C# shell).
Note that you still need to reference them with -r:
compiler option to be able to use their features in the code.
#!/usr/bin/csexec -r:MyLibrary.dll
using System;
using MyLibrary;
public class Program
{
public static void Main (string [] args)
{
var myObject = new MyClass ();
Console.WriteLine (myObject);
}
}
See template scripts in the templates
directory.
csexec
works better along with R7.Scripting library,
which provides various components to simpify C# scripting and easily integrate your scripts with
Nautilus / Nemo / Caja file managers.