我目前正在使用 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/