Execute Bash one-liner with different quotes from Java code for Elasticsearch query

CobraKai :

Im trying to execute a Elastic search post query inside my java code. i want the code to be executed on my machine using the bash shell.

Here is my code:

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);
 }
 }

Ive tried to to it in two different ways, as you can see from the code that has been commented out.

I print the query i constructed in order to verify it. When i execute this program on my local machine and try the printed query in the terminal, it works, but not in my java code/bash query. I guess it has something to do with the formatting and the use of single quotation marks, but i have not yet been able to run it directly from my code.

pitprok :

You could try to write the script in a separate file and then use

String[] cmdScript = new String[]{"/bin/bash", "path/to/myScript.sh"}; 
Process procScript = Runtime.getRuntime().exec(cmdScript);

If you also want to add parameters you could use something like

Process procBuildScript = new ProcessBuilder("path/to/myScript.sh", "myArg1 myArg2").start();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135508&siteId=1