4

This is the command I want to run:

su - postgres -c "pg_dump ....."

to backup the postgres database.

If I am now in linux shell, as a root, it works great.

But now, I want to run it from a java application, as:

String cmd = "su - postgres -c \"pg_dump --port 5432 .....\""
Process p = Runtime.getRuntime().exec(cmd);
// read the error stream and input stream
p.waitFor();

It throws an error:

su: unknown option "--port"
please try "su --help" to get more information

Now I change the code as:

Process p = Runtime.getRuntime().exec(new String[0]{cmd});
// read the error stream and input stream
p.waitFor();

Cannot run program "su - postgres -c \"pg_dump .....\"": java.io.IOException: error=2, no that file or directory

What should I do now?

Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

3
exec(new String[]{"sh", "-c", "su - postgres ..."});
Roland Illig
  • 40,703
  • 10
  • 88
  • 121
3

Besides the answers given above (and it's good to understand your problem) remember that you always can make your life easier by just putting your command inside a shell script file. Eg, a dumppg.sh file which just contains two lines:

#!/bin/sh
su - postgres -c "pg_dump ....."

just make it executable, and (after testing it) call it from java.

leonbloy
  • 73,180
  • 20
  • 142
  • 190