[英]Running bash script from java
我的問題很簡單,當我嘗試從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 '<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;
首先從命令的開頭刪除'bash'。
其次,我不確定shell會做#! 不交互使用時的解釋。 我很想直接跳到/ bin / bash進行Runtime.exec()調用。
最后,簡單地讓一個讀者出現在標准輸出上是不夠的。 您需要主動從它和stderr中讀取,以防止進程在寫入太多輸出時掛起。 為了澄清,在處理任何輸出之前,您正在等待進程完成( proc.waitFor()
)。 如果進程在退出之前寫入太多輸出,它將阻止等待您清空緩沖區,同時阻止等待它退出。
閱讀本文的所有4頁: http : //www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html? page = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.