java中bash应用,从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 '

' ' ' | 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;

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值