peteris.rocks

C# Shell Scripts

How to use C# in shell scripts

Last updated on

Create a launcher script

#!/bin/bash

TEMP_DIR=$(mktemp -d)
SCRIPT=$1
shift

cat $SCRIPT | grep -v '^#!' > $TEMP_DIR/script.cs
mcs $TEMP_DIR/script.cs -out:$TEMP_DIR/script -optimize+
mono $TEMP_DIR/script $@
rm -rf $TEMP_DIR

Make sure it's executable with chmod +x csharp_launcher.

Put it in your $PATH e.g. /usr/local/bin.

Create a script

#!/usr/bin/env csharp_launcher

using System;
using System.IO;

class Program {
 static void Main(string[] args) {
  using (var reader = new StreamReader(Console.OpenStandardInput()))
  using (var writer = new StreamWriter(Console.OpenStandardOutput())) {
   while (!reader.EndOfStream) {
    string line = reader.ReadLine();
    switch (args[0]) {
     case "lower":
     case "lowercase":
      writer.WriteLine(line.ToLower());
      break;
     case "upper":
     case "uppercase":
      writer.WriteLine(line.ToUpper());
      break;
     default:
      writer.WriteLine(line);
      break;
    }
   }
  }
 }
}

Make sure it's executable with chmod +x changecase.cs

Run it!

echo "Ab" | ./changecase.cs lower

Voila!

ab

Requirements

Alternative

Comparison

C#

$ time echo "AbC" | ./changecase.cs uppercase
ABC

real    0m0.416s
user    0m0.372s
sys     0m0.042s
$ time cat 100MB.txt | ./changecase.cs upper > /dev/null

real    0m2.566s
user    0m2.225s
sys     0m0.332s
$ time cat 1GB.txt | ./changecase.cs upper > /dev/null

real    0m22.413s
user    0m19.259s
sys     0m2.988s

Python

#!/usr/bin/env python

import sys

arg = sys.argv[1]

for line in sys.stdin:
 if arg == "lower" or arg == "lowercase":
  print line.lower()
 elif arg == "upper" or arg == "uppercase":
  print line.upper()
$ time echo "ABC" | ./changecase.py upper
real    0m0.028s
user    0m0.011s
sys     0m0.016s
$ time cat 100MB.txt | ./changecase.py upper > /dev/null

real    0m0.756s
user    0m0.617s
sys     0m0.139s
$ time cat 1GB.txt | ./changecase.py upper > /dev/null

real    0m7.985s
user    0m6.281s
sys     0m1.514s