Let's run a Bash script in Java

Introduction

If you create a process with Processbuilder or Runtime in Java, the behavior may not always be the same as the behavior on Linux. If you temporarily create a "bash script (shell script)" and execute it, it may behave as you want.

code


public void executeCommands() throws IOException {

//Temporary file creation
    File tempScript = createTempScript();

    try {
        //Script execution
        ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());

       //Error output
       try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
               System.out.println(buffer.lines().collect(Collectors.joining("\n")));
       }

      //Standard output
      try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
               System.out.println(buffer.lines().collect(Collectors.joining("\n")));
       }
        Process process = pb.start();
        process.waitFor();
    } finally {
        //Temporary file deletion
        tempScript.delete();
    }
}

public File createTempScript() throws IOException {
    //Temporary file creation
    File tempScript = File.createTempFile("script", null);

    Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
            tempScript));
    PrintWriter printWriter = new PrintWriter(streamWriter);

    //I will write a script.
    printWriter.println("#!/bin/bash");
    printWriter.println("cd bin");
    printWriter.println("ls");

  //End of writing
    printWriter.close();

    return tempScript;
}

Reference (plagiarism of this)

https://stackoverflow.com/questions/26830617/running-bash-commands-in-java

Recommended Posts

Let's run a Bash script in Java
Run a multi-line script in a PDB
Run the Python interpreter in a script
A memorandum to run a python script in a bat file
Let's try a shell script
Let's make a cron program in Java! !! (Task Scheduler)
Let's create a script that registers with Ideone.com in Python.
A note for embedding the scripting language in a bash script
Note 2 for embedding the scripting language in a bash script
Let's run "python -m antigravity" in python
How to determine if a shell script was started in bash
Run a local script on a remote host
Let's make a combination calculation in Python
Use Python3's Subprocess.run () in a CGI script
How to run a Maya Python script
Run PIFuHD in Windows + Anaconda + Git Bash environment
I wrote a class in Python3 and Java
How to run some script regularly in Django
[AWS] Let's run a unit test of Lambda function in the local environment
Bash in Jupyter
Let's set and set raspberry wifi in cui script
Let's write a Python program and run it
Call a Python script from Embedded Python in C ++ / C ++
Bash script memo
Run a python script from excel (using xlwings)
Run cbc of "Let's make a normal compiler" with Java 8 or later + 64bit
Let's understand the standard input / output of bash together and write a shell script.
I want to write in Python! (2) Let's write a test
Create a plugin to run Python Doctest in Vim (2)
I made a script to put a snippet in README.md
Create a plugin to run Python Doctest in Vim (1)
What's in that variable (when running a Python script)
Run a Python file with relative import in PyCharm
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
Generate a bash script to add Datadog monitor settings
Facade pattern in Java
Singleton pattern in Java
Flyweight pattern in Java
Observer pattern in Java
Linux permissions in Java
Use DataFrame in Java
Iterator pattern in Java
Decorator pattern in Java
dict in dict Makes a dict a dict
Prototype pattern in Java
Proxy pattern in Java
How to run a Python program from within a shell script
Let's make a spot sale service 4 (in Python mini Hack-a-thon)
I made a Numer0n battle game in Java (I also made AI)
Process the files in the folder in order with a shell script
I wrote a script to get a popular site in Japan
Let's create a function to hold down Button in Tkinter
A set of script files that do wordcloud in Python3
I wrote a script that splits the image in two