使用java运行终端命令来清除终端历史记录

时间:2014-06-01 23:32:46

标签: java

我想获得终极历史记录 所以我做了这个

Runtime rt = Runtime.getRuntime();
pr = rt.exec("/bin/bash -c \"history -c\"");
pr.waitFor();
rt.exec("/usr/bin/xterm");

但是pr = rt.exec存在问题(" / bin / bash -c \"历史记录-c \""); ,它没有清除xterm和我的普通终端的历史记录。

此外,当我尝试打印历史记录时,它不会返回任何内容(没有错误)

p = Runtime.getRuntime().exec("/bin/bash -c \"history\"");
p.waitFor();
BufferedReader reader = 
         new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";       
System.out.println("printing");
while ((line = reader.readLine())!= null) {
    output.append(line + "\n");
}

我也试过

String[] commands = new String[]{"/bin/sh","-c", "history -c" ,"xterm"};
try {
        Process proc = new ProcessBuilder(commands).start();
        BufferedReader stdInput = new BufferedReader(new 
                    InputStreamReader(proc.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
                        InputStreamReader(proc.getErrorStream()));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

仍未清除历史记录。

2 个答案:

答案 0 :(得分:0)

您可以通过获取$ HISTFILE环境变量来自行删除历史记录文件。这将始终为不同的shell获取正确的历史文件。我相信您遇到的问题是您可能正在使用其他shell或更改了您的历史记录文件位置。

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RemoveShellHistory {

    public static void main(String[] args) {
        RemoveShellHistory obj = new RemoveShellHistory();

        final String shellPath = System.getenv("SHELL");
        String shell = shellPath.substring(shellPath.lastIndexOf("/")+1, shellPath.length());
        final String home  = System.getenv("HOME");

        String command = "rm -v " + home + "/." + shell + "_history";
        String output = obj.executeCommand(command);

        System.out.println(output);
    }

    private String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }
            } catch (Exception e) {
            e.printStackTrace();
        }
        return output.toString();
    }
}

答案 1 :(得分:0)

假设您的Java应用程序由拥有.bash_history文件的同一用户运行:

要删除。

new File(System.getProperty("user.home"), ".bash_history").delete();

清理(随意处理已检查的例外)。

    FileWriter writer = new FileWriter(
        new File(System.getProperty("user.home"), ".bash_history"));
    writer.write("");
    writer.close();