Reputation: 10243
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?
Upvotes: 0
Views: 113
Reputation: 878
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.
Upvotes: 1
Reputation: 2286
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();
}
Upvotes: 1