Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - Using Quotes within getRuntime().exec

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 try to invoke the command using getRuntime().exec, I get the following error:

      foo": -c: line 0: unexpected EOF while looking for matching `"'

      foo": -c: line 1: syntax error: unexpected end of file

It seems to be related to my string not being terminated with an EOF.

Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...