Writing a simple Bash interpreter in Python

I wrote a blog post on how to create a bash interpreter in Javascript very recently, but we were limited since I was working in front-end Javascript, but since in Python we can create directories and files, the possibilities are wider, so on this one, we will be going more in-depth and making more commands. Instead of using if…else, we’ll be using the Python equivalent of switch cases.

First, we’ll add echo.

def run2(code):

    string = code.split(' ')
    def notFound():
      print(f"Command not found: {string[0]}")
    def echo():
      prepend = "\n"
      if ("-n" in string):
        string.remove('-n')
        prepend = ""
      tempstring = string.copy()
      tempstring.pop(0)
      print(" ".join(tempstring), end = prepend)

    switchCommand = {
      'echo': echo,
      'notFound': notFound
    }

    switchCommand.get(string[0], notFound)()

You’ll notice that for this one, we’ve actually added an option: “-n” to prevent newlines. And we’ve also added a function for not found. The user could just run the command notFound, right? Yes, but consequentially it would show “Command not found: notFound” because of the way we programmed it. Next, we’ll be making clear. For this we’ll have to import the module os. At the first line of your file, type in from os import system, name, path. We won’t be using path yet, but we’ll need it later. Add the following function to your run() function.

def clear(): 
      if name == 'nt': 
        _ = system('cls') 
      else: 
        _ = system('clear')

Then add 'clear': clear to the switchCommand variable. Now we’ll be making pwd. This is why we needed to import path from os. Add the following code to the run() function and change switchCommand to match (add 'pwd': pwd to switchCommand).

def pwd():
      print(path.dirname(path.realpath(__file__)))

Now let’s add cat:

def cat():
      try :
        f = open(string[1], "r")
        print(f.read())
        f.close()
      except FileNotFoundError:
        print("No such file or directory")
      except IndexError:
        print("No file name")

By now, you should know what to add to switchCommand. I recommend that you take this code and change it and expand it, because that’s as far as I’m going in this blog post.

Leave a Reply

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