Build your own Shell! November 11, 2007
Posted by arpeggiosso in Command Line Applications.Tags: algorithm, command, executing, line, parser, parsing, polish form., shell
trackback
Last week, I was put to the challenge of writing my own command-line interpreter.There are a couple problems which pop-up. Actually there are just three!
- You must find a way of translating the line of text which the user types in, into something that can be read internally by the shell. This is usually done by isolating the simple commands and the operators.
- After that, you must arrange the commands and the operators in such a manner that will allow you to execute them in the correct order.
- Execute them.
Ok. It doesn’t seem much, but it gets really complicated when you are trying to do it for the first time. There are a lot of parsers out there which can make your life a lot easier, but what if you wake up one day and just wonder…how the f…The three problems can be grouped into two modules. The parsing module (containing the 1st and the 2nd issue) and the executing module (the last problem).PARSING THE COMMAND-LINEThe anatomy of the line read form the user is rather simple. It must contain commands and operators defining an order and some relations between the commands.In my project, for example, there were just 4 operators:
- ‘|’ – the pipe operator. If put before two commands, assured that the latter would receive as input, the first’s output.
- ‘&&’ and ‘||’ – conditional operators. The second command was only executed if the return code of the first was either 0 or something different from 0.
- ‘&’ – parallel operator. Makes the two commands work in parallel.
- ‘;’ – sequential operator. Makes sure that the second operation is not started until the first one finishes (either normally or with an error).
Each operator must have it’s own priority, like mathematical operators have priorities (e.g. *-multiply has a higher priority than +-add ). For the above described operators, ‘|’ is the most privileged.Command lines are very much like normal mathematical expresions (e.g. 2+3*4-(5/3) ). So we can look at them from the same perspective. I chose to use the Polish form.
Comments»
No comments yet — be the first.