Search code examples
javalinuxbashprocessexecution

Linux Command not working using java if it contains special symbol


I am trying to run the below code but it is not working, can someone help me understand why it is behaving like this or am i missing something?

import java.io.IOException;

public class SimpleClass {

    public static void main(String args[]){
        try {
            Process process = Runtime.getRuntime().exec("bash mkdir demoDir");
            // Process process2 = Runtime.getRuntime().exec("echo sometext >> someFile.txt");
            }

        catch (IOException e) {
            e.printStackTrace();
        }
    }

}

If i execute the first process it is working fine but if i execute process2 it is not working. someFile.txt is present and the present working directory, apart from this command if i try to make directory like mkdir /home/dummy/demoDir then also it is not working but my program gets executed successfully.


Solution

  • The answer to this question was already discussed here. Use

    String[] cmd = {"bash", "-c", "echo sometext >> someFile.txt" };
    Process process2 = Runtime.getRuntime().exec(cmd);
    

    instead. Works for me.