Using Quotes within getRuntime().exec

谁都会走 提交于 2019-11-27 04:37:08

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. :-))

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

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

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

You can get a shell to the parsing for you if you really wanted. Which would make you example look something like (untested):

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

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

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.

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

E.g.

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

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!