1

I need to start a process in a new console window. For macs, I found something like this: Running a command in a new Mac OS X Terminal window where the command to run is passed as a string.

So I made a method that given a list of Strings (like process builder), returns the list of Strings (the final command) that will run the given command in a new console window. I could append the given strings with spaces, which would work most of the time, but how would I escape it properly? For example, I can pass the process builder new String[] { "echo", "hello world" } and it actually does echo "hello world". And it deals with a lot of other cases too (I think).

I think the explanation is complicated so here is a pseudo-stub:

public static String[] getConsoleCommand(String[] command) {
    if operating system is Mac...
        String commandString = concatenate command...
        return new String[] { "osascript", "-e",
            String.format("'tell application \"Terminal\" to do script \"%s\"'",
                        commandString.replace("'", "\\\'")) // escape single quote used in 'tell application...'
        };
}
Community
  • 1
  • 1
Raekye
  • 5,081
  • 8
  • 49
  • 74

1 Answers1

0
import org.apache.commons.lang.StringEscapeUtils;

for(int i = 0;i <arrayCommand.length();i++) { 
  arrayCommand[i] = StringEscapeUtils.escapeJava(unescapedJava);
}
user650749
  • 182
  • 2
  • 13
  • I don't think that deals with console commands. For example, if the passes `Hello world` as one of the parameters, I need it to escape the space as `Hello\ world` too – Raekye Mar 30 '13 at 03:33
  • I don't understand why you need escape space. when we talk about escape, normally it refer to those chars which will confuse the compiler/parser. In you case, why the ProcessBuilder can't fit your requirement? Or if your command is so complicated, why not put all into a script and just run that script(may be with minimum parameters) – user650749 Mar 31 '13 at 17:32
  • The command I create depends on user input. The space was just an example - basically, I'm no shell expert and am not sure about any other cases I'd need to handle. If you say "All I need to worry about is tokens with spaces be put in quotations and have their quotations escaped", then that'll do. Not sure I am making sense - that more clear? – Raekye Apr 01 '13 at 07:26
  • It's not a good practice to run any input from user as a command under shell. That will have injection risk by which user can run any command such as rm -f *. ProcessBulider is the way to go. in your case, you may not need write very fancy shell script. You can write the input into a file and have your command to process that file. You can process the user input in a controlled way in this way. – user650749 Apr 03 '13 at 01:03
  • It's running on their own computer, in sorta a "do what you want" setting. So I don't really care if they try to delete all their own files :P – Raekye Apr 03 '13 at 09:13