0

I have a problem trying to run an sh script from Java. I've already tried with the solutions to similar problems at stack overflow.

The problem is not the call of the script itself, but the command pg_dump:

=> If I run the following script from console ./my_script.sh everything goes ok:

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

=> But if I want to call it from Java code, the echo command success (so the script has been called) but not the pg_dump command:

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;

My question is why the same script from console success but not calling it from Java?

asked Mar 13, 2015 at 8:36
1
  • 1
    Try putting #!/bin/bash as the first line of your script. Commented Mar 13, 2015 at 8:45

2 Answers 2

1

You can try this

 try {
 ProcessBuilder pb = new ProcessBuilder("script.sh");
 Process p = pb.start(); 
 p.waitFor(); 
 System.out.println("Script executed Finish");
 } 
 catch (Exception e) 
 {
 e.printStackTrace();
 }
answered Mar 13, 2015 at 8:41
Sign up to request clarification or add additional context in comments.

1 Comment

Already; editing my question for give all the exception management. Sorry!
1

I guess pg_dump does some relatively complex stuff with in/out streams so you may have hit some of the pitfals listed in http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html The article has code listings in it which may be helpful in this case.

answered Mar 13, 2015 at 8:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.