Building a simple Bash interpreter in Javascript.

Making your own programming language/building an interpreter for another one is surprisingly easy. It can even be fun and will help you understand how interpreters work (the way I’ll show you isn’t quite how interpreters work though). We will be leaving out things like the ability to echo variables. We’ll be making two commands: echo and npm.

Writing the interpreter

You can find the source code at GitHub

First, we’ll need to create a function to run the code, and since spaces matter in Bash, we’ll .split(" ") the code (and trim the start to remove unnecessary spaces).

function run(code) {
  var string = code.trimStart().split(" ")
}

First, we’ll implement the simplest keyword: echo. (We will do this without any of the options though.)

function run(code) {
  var string = code.trimStart().split(" ")
  if (string[0] == 'echo') {
    var temparr = JSON.parse(JSON.stringify(string))
    temparr.shift()
    console.log(temparr.join(' '))
  }
}

Next, just for fun we’ll make the npm command. It won’t be functional.

function run(code) {
  var string = code.trimStart().split(" ")
  if (string[0] == 'echo') {
    var temparr = JSON.parse(JSON.stringify(string))
    temparr.shift()
    console.log(temparr.join(' '))
  } else if (string[0] == 'npm') {
    if (string.indexOf('i') != -1 || string.indexOf('install') != -1) {
      var temparr = JSON.parse(JSON.stringify(string))
      temparr.shift()
      temparr.shift()
      temparr = temparr.join(' ').trimStart().split(' ')
      console.log('Installed package ' + temparr.join(' '))
    } else if (string.indexOf('uninstall') != -1) {
      var temparr = JSON.parse(JSON.stringify(string))
      temparr.shift()
      temparr.shift()
      temparr = temparr.join(' ').trimStart().split(' ')
      console.log('Uninstalled package ' + temparr.join(' '))
    }
  }
}

If we were to use the above script as an actual bash interpreter, it would lack a lot of the features. It has two commands, and one of them is useless. I highly recommend taking the above code and making it better.

To use this with multiline strings, just simply do this:

var code  = `echo Hello World!
npm i myPackage`
var split = code.split("\n")
for (var i = 0; i < split.length; i++) {
  run(split[i])
}

Leave a Reply

Your email address will not be published. Required fields are marked *