Runtime.exec () cannot run "su-postgres -c" pg_dump ... "

This is the command I want to run:

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

to backup the postgres database.

If I'm in the linux shell now, as a root, it works fine.

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

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

Gives an error message:

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

Now I am changing 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?

+3
source share
2 answers

Besides the answers above (and understanding your problem well), remember that you can always make your life easier by simply placing your command in a shell script file. For example, a file dumppg.shthat contains only two lines:

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

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

+3
source
exec(new String[]{"sh", "-c", "su - postgres ..."});
+2

Source: https://habr.com/ru/post/1782805/