We've established that the shell has lots of the features found in general-purpose programming languages. With that out of the way, I'm going to make the opposite point. Remember that fragment I used as an example of conditional logic in Bash?

# Is it between midnight and 6am?
# (We'll assume that counts as "after midnight".)
if [ "`date '+%H'`" -lt 6 ]; then
  echo "do not feed the mogwai"
fi

This is actually... Well, it's not very much fun dealing with this kind of syntax.

The truth is that, while shell scripting is really useful, it's often not nearly as well suited to writing complicated programs as other languages. If you already know some Python, Perl, Ruby, Node.js, etc., you'll often have a better time using those tools than trying to shoehorn too much into the shell.

As a rough guideline, I usually consider rewriting things in another language once a shell script takes up more than one or two screens in my text editor.

Fortunately, working with other languages than Bash doesn't mean you have to lose the benefits of shell pipelines, standard I/O, and interaction with other utilities.

Following are the equivalents of stars.sh in a handful of popular languages. If you use this basic pattern of reading from standard input and writing to standard out, you can write programs that interact seamlessly with the traditional Unix environment, while benefitting from modern high-level language features and libraries.

Python: stars.py

#!/usr/bin/env python
# encoding: utf-8

import sys
import re

write = sys.stdout.write
line = sys.stdin.readline()

while line:
  stars = re.sub('\S', '★', line)
  write(stars)
  line = sys.stdin.readline()

Perl: stars.pl

#!/usr/bin/env perl

use warnings;
use strict;

while (my $line = <>) {
  $line =~ s/\S/★/g;
  print $line . "\n";
}

Node.js: stars.js

For this one to run, you'll need Node.js. We've got a tutorial on installing Node.js on the Pi, or you can use the Adafruit Pi Finder to install Occidentalis, our growing collection of packages for single-board computers, which includes Node along with other development tools and configuration helpers.

#!/usr/bin/env node

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
  var stars = data.replace(/\S/g, '★');
  process.stdout.write(stars);
});

This guide was first published on Feb 24, 2015. It was last updated on Feb 24, 2015.

This page (Write Shell Utilities in Other Languages) was last updated on Feb 24, 2015.

Text editor powered by tinymce.