在getRuntime()。exec中使用引号 [英] Using Quotes within getRuntime().exec

查看:141
本文介绍了在getRuntime()。exec中使用引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字符串作为输入来调用bash。类似于:

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

sh -l -c "./foo"

我想从Java做到这一点。不幸的是,当我尝试使用 getRuntime()。exec 调用命令时,我收到以下错误:

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

这似乎与我的字符串没有以EOF终止有关。

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

有没有办法将特定于平台的EOF插入Java字符串?或者我应该寻找另一种方法,比如在调用sh之前写入临时脚本?

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" ?

推荐答案

使用此:

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

要点:不要加双引号。仅在shell中编写命令行时使用!

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

例如, echoHello,world!(在shell中输入)被转换为:

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

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

(暂时忘记shell通常内置 echo ,并且正在调用 / bin / echo 。: - ))

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

这篇关于在getRuntime()。exec中使用引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆