marco525
marco525

Reputation: 50

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.

Upvotes: 0

Views: 184

Answers (3)

Brosch
Brosch

Reputation: 98

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.

Upvotes: 1

jvaclavovic
jvaclavovic

Reputation: 1

You cannot execute echo command without shell -> add bash to begin of th

Upvotes: -1

Matthew
Matthew

Reputation: 113

>> is interpreted and processed by your shell (e.g., bash, zsh, etc). However, you're not running a shell in this command. Runtime.exec() basically executes the command /bin/echo and passes it the arguments someText, >>, someFile.txt.

I don't know why you want to do what you're doing but try this:

Runtime.getRuntime().exec("bash -c \"echo sometext >> someFile.txt\"");

Upvotes: 1

Related Questions