我正在尝试在我的 java 代码中执行 Elastic search post 查询。我希望使用 bash shell 在我的机器上执行代码。
这是我的代码:
public class Elastic {
public static void main(String[] args) {
String cmd = "curl -X PUT IP:PORT/twitter/_doc/10 -H 'Content-Type: application/json' -d '{ \"user\" : \"Bob\", \"post_date\" : \"2019-12-15T14:12:10\", \"message\" : \"trying out Elasticsearch\" }' ";
try {
Process pr = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
}
/*
try {
Runtime.getRuntime().exec("/bin/bash "+"-c "+"\'"+cmd+"\'");
} catch (Exception e) {
e.printStackTrace();
} */
System.out.println("===============");
System.out.println(cmd);
}
}
我尝试过两种不同的方式,正如您从已注释掉的代码中看到的那样。
我打印我构造的查询以验证它。当我在本地计算机上执行此程序并尝试在终端中打印查询时,它可以工作,但不能在我的 java 代码/bash 查询中工作。我想这与格式和单引号的使用有关,但我还无法直接从我的代码运行它。
最佳答案
您可以尝试将脚本编写在单独的文件中,然后使用
String[] cmdScript = new String[]{"/bin/bash", "path/to/myScript.sh"};
Process procScript = Runtime.getRuntime().exec(cmdScript);
如果您还想添加参数,您可以使用类似的内容
Process procBuildScript = new ProcessBuilder("path/to/myScript.sh", "myArg1 myArg2").start();
关于java - 使用 Java 代码中的不同引号执行 Bash 单行代码以进行 Elasticsearch 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108341/