Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running bash script from java

Tags:

java

bash

my problem is simple, when I try to run .sh script from Java, the script doesnt execute. If I change my script to a simple linux command, such as ls -all, it works perfectly, so I guess that I am using a bad command in my script, which stops the execution. Please help.

David

Java code:

    String cmd = "bash /home/david/burza/getter.sh";

    try {
        Process proc = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmd});
        BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        try {
            proc.waitFor();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
        while (read.ready()) {
            System.out.println(read.readLine());
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

Bash script:

#! /bin/bash 

wget -O data1.html http://www.rmsystem.cz/kurzy-online/akcie/easyclick;
touch ext_data.txt; 

grep 'table class="tbl1"' ./data1.html | tr '<td>' ' ' | tr '-' 'A' | grep -o -w '[0-9, ]*' | sed 's/  *//g' | sed '/^$/d' | tr ',' '.' > ext_data.txt;

lines=`wc -l ext_data.txt | grep -o '[0-9]*'`;

( echo $lines; cat ext_data.txt ) > ext_data.txt.new && mv ext_data.txt.new ext_data.txt;
like image 457
dawe134 Avatar asked Nov 04 '22 03:11

dawe134


1 Answers

Start by removing the 'bash' from the start of the command.

Second, I'm not sure the shell will do #! interpretation when not used interactively. I would be minded to jump straight to /bin/bash for the Runtime.exec() call.

Finally, simply having a reader present on the stdout is not going to be enough. You need to actively be reading from it, and from stderr, to prevent the process from hanging if it writes too much output. To clarify, you're waiting for the process to complete (proc.waitFor()) before dealing with any of the output. If the process writes too much output before exiting, it will block waiting for you to empty the buffer while you're blocked waiting for it to exit.

Read all 4 pages of this article: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

like image 141
dty Avatar answered Nov 09 '22 17:11

dty