[开源项目]Shell4Win,一个在Windows下执行shell命令的解释器

背景

         顺利拿到心目中的理想offer以后,内心的负担一下减轻了不少,但愿利用还没毕业以前这段可贵的清闲时间作一点有意义的事情。因而但愿能作一个长久以来都想作的开源项目,就是题中提到的Windows下的shell解释器,之因此选择这个是由于以前在数据中心实习,shell脚本用的驾轻就熟,可是由于平时开发脱离不开windows,常常要写一些bat脚本自动化小工具,以为batch的语法和参数都很奇葩。所以萌生了写一个shell解释器的想法,固然后来由于工做量的缘故,去掉了一些shell的特性,保留了一些易于实现、常用且工做量不是太大的特性,好比管道、分号分隔命令、重定向等。这篇文章我会介绍整个开发过程当中须要的知识背景和具体思路实现,源代码和可执行文件已上传至个人GITHUB,欢迎关注。html

    

用到的技术

   首先,要解释任何语言,必然要作词法分析和语法分析。固然,若是你就用正则表达式也能识别部分语法,可是相对来讲,正则的能力有限,并且所需的代码量也会比较复杂(相对使用lex和yacc这种生成工具来讲)。这里分享一个对我颇有帮助的资料:http://pchou.info/resource/2013/12/31/compiler.htmlpython

其次就是具体用什么编写了,最初我有两种备选方案:C和python,这两种语言来编写各自有各自的优点。C能够直接用lex和yacc来生成词法分析器和语法分析器,lex和yacc的规则文件功能也很强大,帮助资源也很丰富。可是lex和yacc的Win32版本实际用下来以后发现并不理想,有些原有规则并不能很好的支持,并且Windows C编程适用面较窄,可能对我产生不了太大的学习价值。而python的PLY(lex和yacc的python一种实现)实际使用下来以后感受很好,并且定义词法语法规则甚至比lex和yacc还要简单。所以最后肯定了使用python来编写这个解释器Shell4Wingit

   搞定词法和语法分析以后就相对简单不少了,咱们从输入读取命令后根据语法分析的结果获取要执行命令的名称和参数(若是语法正确的话),而后绑定相应的方法。没有对应的命令就提示命令不存在。github

        

存在的问题

         正如前面提到的,shell的不少功能都没有提供支持,好比argument,就是诸如”ls –l”里面的”-l”,主要是由于shell里几乎每一个命令都提供了至关多的参数,以致于要把这些命令的参数都实现的话,就是一个很庞大的工程了。所以个人作法是实现经常使用命令的经常使用参数,好比咱们使用ls命令的时候每每是ls –l每一个文件做为一行返回。这样作能够在知足大部分平常须要的状况下缩减工做量。下面一个示例脚本的执行结果:正则表达式

   

[Administrator@PC-20121113XYVZ]#cat example.sh
echo "#This is a example shell script written to demostrate a shell interpreter named Shell4Win#"

echo "Let's start with some simple commands"

echo "ls can show files under current directory:"

ls

read "Press Enter key to continue"

echo "pwd can show you current directory:"

pwd

read "Press Enter key to continue"

echo "mkdir can make a directory,and grep can be used with pipes:"

mkdir test

ls|grep test

echo "cd can change current directory:"

cd test

echo "redirection can create files:"

echo "test content1">1

echo "test content2">2

cat 1

cat 2

echo "diff can be used to compare two text files:"

diff 1 2


[Administrator@PC-20121113XYVZ]#sh example.sh
#This is a example shell script written to demostrate a shell interpreter named Shell4Win# 
Let's start with some simple commands 
ls can show files under current directory: 
example.sh
parser.out
parsetab.py
parsetab.pyc
ply
Shell4Win.py
tools.py
tools.pyc
utilities.py
utilities.pyc
Press Enter key to continue 
pwd can show you current directory: 
C:\Users\Administrator\Documents\GitHub\Shell4Win\src
Press Enter key to continue 
mkdir can make a directory,and grep can be used with pipes: 
Directory test created!
test
cd can change current directory: 
change current directory to test
redirection can create files: 
test content1 
test content2 
diff can be used to compare two text files: 
line 1:   test content1     test content2 

 

 

 

后记

         在这个项目以前,我最喜欢的语言是Java,如今是python!shell

相关文章
相关标签/搜索