从Java运行shell脚本

时间:2015-03-13 08:36:54

标签: java bash shell sh processbuilder

我在尝试从Java运行 sh 脚本时遇到问题。我已经试过了 similar problems at stack overflow的解决方案。

问题不在于脚本本身的调用,而是命令 pg_dump

=>如果我从控制台./my_script.sh运行以下脚本,一切正常:

NOW="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILE="backup_${NOW}.sql"    
FOLDER="./backups"
if [ ! -d "$FOLDER" ]; then
  mkdir $FOLDER
fi
OUTPUT=${FOLDER}/${BACKUP_FILE}

HOST="my.host.dir"
PORT="8080"
DB_NAME="dbName"
USER="user"
PASS="pass"

OPT="-h ${HOST} -p ${PORT} -U ${USER} -f ${OUTPUT} -c -C -i -b -v ${DB_NAME}"
EXPORT="export PGPASSWORD=${PASS}"
RUN="pg_dump ${OPT}"
echo ${EXPORT}
echo ${RUN}
$EXPORT
$RUN

=>但是,如果我想从Java代码中调用它,echo命令成功(因此脚本已被调用),而不是pg_dump命令:

int exitValue = 0;
try {
  ProcessBuilder pb = new ProcessBuilder(scriptPath);
  Process p = pb.start();
  BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
  String line = null;
  while ((line = reader.readLine()) != null) {
    LOG.log(Level.FINE, line);
  }
  exitValue = p.waitFor();
  LOG.log(Level.FINE, "Process exitValue: " + exitValue);
} catch (IOException | InterruptedException e) {
  LOG.log(Level.SEVERE, "Executing " + scriptPath, e);
  return false;
}
return exitValue == 0;

我的问题是为什么同一个脚本来自控制台成功而不是从Java调用它?

2 个答案:

答案 0 :(得分:1)

你可以试试这个

 try {
       ProcessBuilder pb = new ProcessBuilder("script.sh");
       Process p = pb.start();     
       p.waitFor();                
       System.out.println("Script executed Finish");
     } 
     catch (Exception e) 
     {
      e.printStackTrace();
    }

答案 1 :(得分:1)

我猜pg_dump会对输入/输出流做一些相对复杂的事情,所以你可能会遇到http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html中列出的一些pitfals文章中有代码清单,在这种情况下可能会有所帮助。