Rm -rf doesn't work with home tilde in java runtime
This is my code for deleting a folder, this below code does not delete the Downloads directory under the home folder.
import java.io.IOException;
public class tester1{
public static void main(String[] args) throws IOException {
System.out.println("here going to delete stuff..!!");
Runtime.getRuntime().exec("rm -rf ~/Downloads/2");
//deleteFile();
System.out.println("Deleted ..!!"); }
}
However, if I give the full home path, this works:
import java.io.IOException;
public class tester1{
public static void main(String[] args) throws IOException {
System.out.println("here going to delete stuff..!!");
Runtime.getRuntime().exec("rm -rf /home/rah/Downloads/2");
//deleteFile();
System.out.println("Deleted ..!!");
}
}
Can someone tell me what I am doing wrong?
source to share
The tilde ( ~
) is expanded by the shell. When you call exec
, no wrapper is invoked and the binary rm
is invoked immediately and hence the tildes are not expanded. They are not wildcards and environment variables.
There are two solutions. Alternatively, replace the tilde like this:
String path = "~/Downloads/2".replace("~", System.getProperty("user.home"))
or invoke a shell by first attaching your command line
Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");
source to share
Tilde expansion is done by the shell (like bash), however you are doing it rm
directly so that the shell doesn't interpret ~
. I highly recommend not relying on wrapper calls for such functions - they are error prone, have poor security properties, and limit the operating systems your code can run on.
However, if you do decide to use this particular method, you can do:
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "rm -rf ~/Downloads/2" })
source to share