[開源項目]Shell4Win,一個在Windows下執行shell命令的解釋器


背景

         順利拿到心目中的理想offer之后,心里的負擔一下減輕了很多,希望利用還沒畢業之前這段難得的悠閑時間做一點有意義的事情。於是希望能做一個長久以來都想做的開源項目,就是題中提到的Windows下的shell解釋器,之所以選擇這個是因為之前在數據中心實習,shell腳本用的得心應手,但是因為平時開發脫離不開windows,經常要寫一些bat腳本自動化小工具,覺得batch的語法和參數都很奇葩。因此萌生了寫一個shell解釋器的想法,當然后來因為工作量的緣故,去掉了一些shell的特性,保留了一些易於實現、經常使用且工作量不是太大的特性,比如管道、分號分隔命令、重定向等。這篇文章我會介紹整個開發過程中需要的知識背景和具體思路實現,源代碼和可執行文件已上傳至我的GITHUB,歡迎關注。

    

用到的技術

   首先,要解釋任何語言,必然要做詞法分析和語法分析。當然,如果你就用正則表達式也能識別部分語法,但是相對來說,正則的能力有限,而且所需的代碼量也會比較復雜(相對使用lex和yacc這種生成工具來說)。這里分享一個對我很有幫助的資料:http://pchou.info/resource/2013/12/31/compiler.html

其次就是具體用什么編寫了,最初我有兩種備選方案:C和python,這兩種語言來編寫各自有各自的優勢。C可以直接用lex和yacc來生成詞法分析器和語法分析器,lex和yacc的規則文件功能也很強大,幫助資源也很豐富。但是lex和yacc的Win32版本實際用下來之后發現並不理想,有些原有規則並不能很好的支持,而且Windows C編程適用面較窄,可能對我產生不了太大的學習價值。而python的PLY(lex和yacc的python一種實現)實際使用下來之后感覺很好,而且定義詞法語法規則甚至比lex和yacc還要簡單。因此最后確定了使用python來編寫這個解釋器Shell4Win

   搞定詞法和語法分析之后就相對簡單很多了,我們從輸入讀取命令后根據語法分析的結果獲取要執行命令的名稱和參數(如果語法正確的話),然后綁定相應的方法。沒有對應的命令就提示命令不存在。

        

存在的問題

         正如前面提到的,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!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM