从java运行bash脚本

我的问题很简单,当我尝试从Java运行.sh脚本时,脚本不会执行。 如果我将我的脚本更改为简单的linux命令,例如ls -all,它可以正常工作,所以我猜我在脚本中使用了一个错误的命令,这会停止执行。 请帮忙。

大卫

Java代码:

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脚本:

 #! /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; 

首先从命令的开头删除’bash’。

其次,我不确定shell会做#! 不交互使用时的解释。 我很想直接跳到/ bin / bash进行Runtime.exec()调用。

最后,简单地让一个读者出现在标准输出上是不够的。 您需要主动从它和stderr中读取,以防止进程在写入太多输出时挂起。 为了澄清,在处理任何输出之前,您正在等待进程完成( proc.waitFor() )。 如果进程在退出之前写入太多输出,它将阻止等待您清空缓冲区,同时阻止等待它退出。

阅读本文的所有4页: http : //www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html? page = 1