首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找以前的工作目录以实现"cd -“。

查找以前的工作目录以实现"cd -“。
EN

Stack Overflow用户
提问于 2014-02-05 16:01:37
回答 2查看 705关注 0票数 3

我目前正在使用Java编程语言实现一个功能有限的shell。该外壳的范围也有限制要求。任务是尽可能多地对建模。

当我实现cd命令选项时,我引用了一个基本Shell命令页,它提到cd能够返回到命令"cd -“中的最后一个目录。

因为我只获得了一个与方法public String execute(File presentWorkingDirectory, String stdin)的接口。

我想知道是否有来自Java的API调用,我可以检索上一个工作目录,还是这个命令有什么实现?

我知道一个简单的实现是声明一个变量来存储上一个工作目录。但是,我目前有shell本身(包含选项的命令),每次执行命令工具时,都会创建一个新线程。因此,我认为“主”线程存储前一个工作目录是不可取的。

更新(6-3月-‘14):感谢您的建议!我现在已经和shell的编码器讨论过了,并添加了一个额外的变量来存储上一个工作目录。下面是用于共享的示例代码:

代码语言:javascript
复制
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;
}

}

请注意,这不是代码的完全实现,这也不是cd的全部功能。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-05 16:40:13

Real (至少Bash) shell在PWD环境变量中存储当前的工作目录路径,在OLDPWD中存储旧的工作目录路径。重写PWD不会改变您的工作目录,但是重写OLDPWD确实会改变cd -将带您去的地方。

试试这个:

代码语言:javascript
复制
cd /tmp
echo "$OLDPWD"          # /home/palec
export OLDPWD='/home'
cd -                    # changes working directory to /home

我不知道如何实现shell功能(即如何表示当前的工作目录;通常它是进程的固有属性,由内核实现),但是我认为您确实必须将旧的工作目录保存在一个额外的变量中。

顺便说一句,shell还为执行的每个命令分叉(内部命令除外)。当前工作目录是进程的属性。当命令启动时,它可以更改其内部当前工作目录,但不影响shell的工作目录。只有cd命令(这是内部的)可以更改shell的当前工作目录。

票数 2
EN

Stack Overflow用户

发布于 2014-02-05 16:43:46

如果您希望保存多个工作目录,只需创建一个LinkedList,在其中添加每个新的presentWorkingDirectory,如果您想返回,请使用linkedList.popLast获取最后一个workingDirectory。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21582143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档