Reputation: 339
tried multiple ways. Command to delete files under a set of directories except one specific subdirectory works fine when commmand run on Linux.
Same command when run via Java exec doesn't seem to recognize the path and everything gets wiped out.
find /test/filesdir/filexp -maxdepth 2 ! -path "/test/filesdir/filexp/node1/*" -type f -daystart -mtime +1 -delete
tried escpace character \ before the (") double quotes nothing seems to help.
any thoughts, please help.
java code used:
Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);
RunCmdLine.waitFor();
InputStream stdInput = RunCmdLine.getInputStream();
InputStream stdError = RunCmdLine.getErrorStream();
byte buffer[] = new byte [2048];
for (int read; (read = stdInput.read(buffer)) != -1;) {
System.out.write(buffer, 0, read);
inBuff.append(new String(buffer, 0, read));
}
SystemErrMsg[0] = SystemErrMsg[0] + inBuff.toString();
i get the command line string from a database lookup where i have the entire find command
I added a sysout(commandline) right before the
Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);
and i see the command in the stdout file on the server. It looks good, when i run that command on the server it works fine.
Upvotes: 0
Views: 2341
Reputation: 123550
Runtime.exec(String)
claims another victim!
Never use this function. It has exactly zero valid use cases. Use the Runtime.exec(String[])
version instead, or (even better) ProcessBuilder
.
Both have two commonly used idioms. The first emulates C's simple and sloppy system
by running the command in a shell:
// I don't care about security, my homework is due and I just want it to work ;_;
String CommandLine = "find /test/filesdir/filexp -maxdepth 2 "
+ "! -path \"/test/filesdir/filexp/node1/*\" "
+ "-type f -daystart -mtime +1 -delete";
Runtime.getRuntime().exec(new String[] { "bash", "-c", CommandLine });
and a secure and robust version closer to C's execv(char*, char**)
:
// I have a strong understanding of UNIX and want a robust solution!
String[] commandArgs = new String[] {
"find", "/test/filesdir/fileexp", "-maxdepth", "2",
"!", "-path", "/test/filesdir/filexp/node1/*", "-type", "f",
"-daystart", "-mtime", "+1", "-delete"
};
Runtime.getRuntime().exec(commandArgs);
The first just requires you to know how to use a shell. The second requires you to additionally know how a shell works behind the scenes, and can not be blindly copied based on this example.
Upvotes: 1