rm -rf doesnt work with home tilde in java runtime

1.7k views Asked by At

This is my code to delete a folder , this below code wont delete the Downloads directory under 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 complete 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 anybody tell me what am I doing wrong.?

4

There are 4 answers

2
user207421 On

You're using shell syntax without a shell. Change the command to this:

new String[]{"sh", "-c", "rm -rf ~/Downloads/2"}
3
vidstige On

The tilde (~) is expanded by the shell. When you call exec no shell is invoked, but rather the rm binary is called immediately and thus tildes are not expanded. Nor are wildcards and environment variables.

There are two solutions. Either replace tilde yourself like so:

String path = "~/Downloads/2".replace("~", System.getProperty("user.home"))

or call a shell by prefixing your command line like so

Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");
0
Jasvir On

The tilde expansion is done by the shell (eg. bash), however, you are running rm directly so there is no shell to interpret the ~. I'd strongly recommend not relying on calling out to the shell for such functions - they are error-prone, have poor security properties and limit the operating systems on which your code can run.

However, if you really determined to use this particular method, you can do:

Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "rm -rf ~/Downloads/2" })

0
Ai Suzuki On

You could use an environment variable such as $HOME if using tilde is not necessary.

String homeDir = System.getenv("HOME"); Runtime.getRuntime().exec("rm -rf " + homeDir + "/Downloads/2");