在Java中执行Linux命令时的单引号问题 [英] Single quote Issue when executing Linux command in Java

查看:539
本文介绍了在Java中执行Linux命令时的单引号问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Runtime.getRuntime().exec()执行这样的Linux命令:

I need to execute Linux command like this using Runtime.getRuntime().exec() :

/opt/ie/bin/targets --a '10.1.1.219 10.1.1.36 10.1.1.37'

基本上,此命令是将每个目标一个接一个地连接到服务器(10.1.1.219、10.1.1.36、10.1.1.37).在终端上运行良好,结果应该是:

Basically, this command is to connect each targets to server one by one (10.1.1.219, 10.1.1.36, 10.1.1.37). It works well in terminal, the result should be :

['10.1.1.219', '10.1.1.36', '10.1.1.37']

但是,如果我使用Runtime.getRuntime().exec(execute)执行命令,就像这样:

But if I execute the command using Runtime.getRuntime().exec(execute), like this :

execute = "/opt/ie/bin/targets" + " " + "--a" + " " + "'" + sb
                + "'";

Java将单引号视为要执行的字符串,结果将是:

Java will treat the single quote as string to execute, the result will be :

callProcessWithInput executeThis=/opt/ie/bin/targets --a '10.1.1.219 10.1.1.36 10.1.1.37' 
The output for removing undesired targets :["'10.1.1.219"] 

有人知道如何解决吗?谢谢!

Anyone knows how to solve it? Thanks!

推荐答案

shell解释了引号字符,以控制它如何将命令行拆分为参数列表.但是,当您从Java调用 exec 时,您并没有使用shell.您正在直接调用该程序.当您将单个 String 传递给 exec 时,它会使用 StringTokenizer 拆分为命令参数,该参数仅在空白处拆分并且不给出引号有特殊含义.

Quote characters are interpreted by the shell, to control how it splits up the command line into a list of arguments. But when you call exec from Java, you're not using a shell; you're invoking the program directly. When you pass a single String to exec, it's split up into command arguments using a StringTokenizer, which just splits on whitespace and doesn't give any special meaning to quotes.

如果要对传递给程序的参数进行更多控制,请调用带有 String [] 参数的 exec 版本之一.这跳过了 StringTokenizer 步骤,并允许您指定被调用程序应接收的确切参数列表.例如:

If you want more control over the arguments passed to the program, call one of the versions of exec that takes a String[] parameter. This skips the StringTokenizer step and lets you specify the exact argument list that the called program should receive. For example:

String[] cmdarray = { "/opt/ie/bin/targets", "--a", "10.1.1.219 10.1.1.36 10.1.1.37" };
Runtime.getRuntime().exec(cmdarray);

这篇关于在Java中执行Linux命令时的单引号问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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