2012-03-20 140 views
5

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

大卫

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

您确定您的脚本设置为可执行吗?也许chmod + x script.sh可以帮助 – Kiwy 2012-03-20 16:52:34

+0

你期望得到什么?你的shell脚本不会输出任何标准输出,它将所有输出重定向到文件。那么什么是BufferedReader? – zserge 2012-03-20 17:07:32

+0

这是一个愚蠢的代码,为输入,输出和错误流编写3个线程并以交互方式执行,这将为您节省各种麻烦 – 2013-03-07 10:44:20

回答

2

开始通过从命令开始的 '庆典'。

其次,我不确定shell会做#!没有交互使用时的解释。我会心甘情愿地为Runtime.exec()调用直接跳到/ bin/bash。

最后,仅仅在stdout上有一个阅读器是不够的。你需要积极地阅读它,并从stderr,以防止过程挂起,如果它写太多的输出。为了澄清,在处理任何输出之前,您需要等待处理完成(proc.waitFor())。如果进程在退出之前写入的输出太多,它将阻止等待您清空缓冲区,同时阻止等待它退出。

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

+0

非常感谢您的建议,我设法使用http:// www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1非常感谢。 – dawe134 2012-04-05 22:13:46