[開源項目]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

相關文章
相關標籤/搜索