2014-02-05 35 views
3

我目前正在使用Java編程語言實現一個功能有限的shell。 shell的範圍也有限制的要求。我的任務是儘可能地模擬一個Unix shell。尋找以前的工作目錄來實現「cd - 」

當我執行cd命令選項時,我引用Basic Shell Commands page,它提到cd能夠返回到我使用命令「cd-」訪問的最後一個目錄。

由於我只給出了與方法public String execute(File presentWorkingDirectory, String stdin)的接口。

我想知道是否有來自Java的API調用,我可以檢索以前的工作目錄,或者如果有此命令的任何實現?

我知道一個簡單的實現是聲明一個變量來存儲以前的工作目錄。不過,我目前擁有shell本身(帶有選項的命令),每次執行一個命令工具時,都會創建一個新線程。因此,我認爲「主」線程不宜存儲以前的工作目錄。

更新(6-Mar-'14):感謝您的建議!我現在已經與編碼器討論了shell,並添加了一個額外的變量來存儲以前的工作目錄。下面是共享的代碼示例:

public class CdTool extends ATool implements ICdTool { 
    private static String previousDirectory; 

    //Constructor 
    /** 
    * Create a new CdTool instance so that it represents an unexecuted cd command. 
    * 
    * @param arguments 
    * the argument that is to be passed in to execute the command 
    */ 
    public CdTool(final String[] arguments) { 
     super(arguments); 
    } 

    /** 
    * Executes the tool with arguments provided in the constructor 
    * 
    * @param workingDir 
    *   the current working directory path 
    * 
    * @param stdin 
    *   the additional input from the stdin 
    * 
    * @return the message to be shown on the shell, null if there is no error 
    *   from the command 
    */ 
    @Override 
    public String execute(final File workingDir, final String stdin) { 
     setStatusCode(0); 
     String output = ""; 

     final String newDirectory; 

     if(this.args[0] == "-" && previousDirectory != null){ 
      newDirectory = previousDirectory; 
     } 
     else{ 
      newDirectory = this.args[0]; 
     } 

     if(!newDirectory.equals(workingDir) && 
      changeDirectory(newDirectory) == null){ 
      setStatusCode(DIRECTORY_ERROR_CODE); 
     output = DIRECTORY_ERROR_MSG; 
    } 
    else{ 
     previousDirectory = workingDir.getAbsolutePath(); 
     output = changeDirectory(newDirectory).getAbsolutePath(); 
    } 

    return output; 
} 

} 

P.S:請注意,這是不完整的執行代碼,這是不是光盤的全部功能。

+0

如果您只想回到一個級別,請使用變量,如果您想返回更多級別,請維護一個堆棧。 – Kent

回答

2

真正的shell(至少Bash)shell在PWD環境變量和舊工作目錄路徑OLDPWD中存儲當前工作目錄路徑。重寫PWD不會更改您的工作目錄,但重寫OLDPWD確實會更改,其中cd -將帶您。

試試這個:

cd /tmp 
echo "$OLDPWD"   # /home/palec 
export OLDPWD='/home' 
cd -     # changes working directory to /home 

我不知道你是怎麼實現的外殼的功能(你即如何代表當前工作目錄;通常是過程的固有屬性,由內核來實現),但我認爲你必須將舊的工作目錄保存在一個額外的變量中。

順便說一下,shell還爲每個執行的命令分配(除了內部的命令)。當前工作目錄是進程的屬性。當一個命令啓動時,它可以改變它的內部當前工作目錄,但它不會影響shell的。只有cd命令(這是內部命令)可以更改shell的當前工作目錄。

1

如果您想要保留多個工作目錄,只需創建一個LinkedList,然後在and處添加每個新的presentWorkingDirectory,並且如果要返回使用linkedList.popLast即可獲取上一個workingDirectory。

+0

我認爲@Kent在問題下面提出的解決方案更好。你應該使用堆棧來實現這樣的功能。 Stack是基於數組的,所以它沒有指針(在本例中是引用)和節點分配(可能它們是以某種方式預先分配的;不知道Java的膽量)的開銷。 – Palec

+0

沒錯,那樣做會差不多。如果你使用ArrayLists,那麼它確實是一樣的。我只是認爲LinkedList會非常有用,因爲列表的長度可能會有很大的變化,其中LinkedLists比基於數組的列表/堆棧更好。 – Dakkaron

+1

對不起,我忘了堆棧應該容納什麼。事實上,當記住工作目錄更改的歷史記錄時,鏈接列表是最佳解決方案。如果想保留所有的歷史記錄 - 當只需要固定數量的最後工作目錄時,循環緩衝區(基於數組的deque)更好。 – Palec