java - 寻找以前的工作目录来实现 "cd -"

标签 java shell directory cd

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

当我执行 cd 命令选项时,我引用了一个 Basic Shell Commands page ,它提到 cd 可以使用命令“cd -”返回到我所在的最后一个目录。

因为我只得到一个接口(interface),方法是 public String execute(File presentWorkingDirectory, String stdin)

我想知道是否有来自 Java 的 API 调用,我可以检索以前的工作目录,或者这个命令是否有任何实现?

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

更新(2014 年 3 月 6 日):感谢您的建议!我现在已经与 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:请注意,这不是代码的完整实现,也不是 cd 的全部功能。

最佳答案

真正的 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 还会为每个执行的命令进行 fork (内部命令除外)。当前工作目录是进程的属性。启动命令时,它可以更改其内部当前工作目录,但不会影响 shell 的工作目录。只有 cd 命令(内部命令)可以更改 shell 的当前工作目录。

关于java - 寻找以前的工作目录来实现 "cd -",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21582143/

相关文章:

java - java中的整数赋值

java - 如何找到我的 java jdk 文件夹并编辑路径变量 - 集成 Maven

java - 在 JTable 中监听 KeyEvent - 如何在编辑单元格时执行此操作?

linux - 查找并删除文件但不是特定路径

bash - UNIX/Linux shell 脚本 : Removing variant form emoji from a text

C# 测试用户是否具有对文件夹的写入权限

java - 简单的 Java Json 到数组

unix - 如何将 shell session 的所有控制台输出发送到日志文件

java - 通过目录搜索

java - Eclipse 导出文件 jar 不包含文件夹