简体   繁体   中英

Runtime.exec() can't 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 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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM