Using Quotes within getRuntime().exec

前端 未结 6 793
不思量自难忘°
不思量自难忘° 2020-11-30 06:46

I\'d like to invoke bash using a string as input. Something like:

sh -l -c \"./foo\"

I\'d like to do this from Java. Unfortunately, when I

相关标签:
6条回答
  • 2020-11-30 07:03

    Use this:

    Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"});
    

    Main point: don't put the double quotes in. That's only used when writing a command-line in the shell!

    e.g., echo "Hello, world!" (as typed in the shell) gets translated to:

    Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"});
    

    (Just forget for the moment that the shell normally has a builtin for echo, and is calling /bin/echo instead. :-))

    0 讨论(0)
  • 2020-11-30 07:03

    The cause for this error is most likely a missing syntax token that bash expects but the string you pass ends before bash encountered it. Look for ifs, fors etc. that have no closing fi or done.

    0 讨论(0)
  • 2020-11-30 07:12

    Windows command lines behave differently from UNIX, Mac OS X and GNU/Linux.

    On Windows the process receives the input text verbatim after the executable name (and space). It's then up to the program to parse the command line (which is usually done implicitly, the programmer is often clueless about the process).

    In GNU/Linux the shell processes the command line, guaranteeing the familiar array of strings passed to C's main function. You don't have that shell. The best approach (even on Windows) is to use one of the form of exec where you pass each command line argument individually in its own String.

    Process exec​(String[] cmdarray)    
    Process exec​(String[] cmdarray, String[] envp)     
    Process exec​(String[] cmdarray, String[] envp, File dir)
    

    Or better, java.lang.ProcessBuilder.

    You can get a shell to do the parsing for you if you really want. This would make your example look something like (untested):

    Runtime.getRuntime().exec(new String[] {
        "sh", "-c", "sh -l -c \"echo foo; echo bar;\""
    });
    
    0 讨论(0)
  • 2020-11-30 07:17

    if I were you, I would write the contents of the string to a temp bashfile and see if bash executes that without any error. If that executes without an error, then I would consider debugging further;

    0 讨论(0)
  • 2020-11-30 07:20

    Quotes need to be escaped when inside a string. Instead of writing " write \".

    E.g.

    strcpy(c, "This is a string \"with\" quotes");

    0 讨论(0)
  • 2020-11-30 07:23

    EOF is NOT a character, so there's no way to write an EOF. You've forgotten to close a quoted string.

    0 讨论(0)
提交回复
热议问题