简体   繁体   English

如何在反斜杠中使用Runtime.exec()?

[英]How to use Runtime.exec() with backslash?

I try to start an shell script from a detached screen in java. 我尝试从Java的分离屏幕启动Shell脚本。

Runtime.getRuntime().exec("screen -S " + code + " -X stuff \"bash start.sh $(printf \\\\r)\"");

I think a " is replaced with \\" and \\ with \\\\ . 我认为"被替换为\\"\\\\\\

The normal code which should be executed is 应该执行的普通代码是

screen -S VMD54 -X stuff "bash start.sh $(printf \\r)"

That starts start.sh from the detached screen eg VMD54 (String code). 从分离的屏幕(例如VMD54 (字符串代码))开始start.sh

What is wrong with my code? 我的代码有什么问题? Nothing happens in the screen VMD54 . 屏幕VMD54没有任何反应

It's better to use ProcessBuilder than exec . 使用ProcessBuilder比使用exec更好。 Either way, use the version that uses separate parameters. 无论哪种方式,请使用使用单独参数的版本。 This is because the version that uses one long string does not break that string the way you think - it mostly just breaks it on spaces and disregards the quotes, passing them as part of the command. 这是因为使用一个长字符串的版本不会像您想象的那样打断该字符串-它只会在空格上打断它,而忽略引号,并将其作为命令的一部分传递。

When you do that, you should consider that what you write on the command line is not what the process actually receives in the end. 在执行此操作时,应考虑在命令行上写的内容并不是该过程最终实际收到的内容。 The command line interpreter - bash in your case - does several things. 命令行解释器-在您的情况下为bash-可完成多项操作。 It expands stuff that begins with $ . 它扩展了以$开头的内容。 It removes the quotes but treats everything inside them as one parameter. 它删除引号,但将其中的所有内容都视为一个参数。 So when you have the command: 因此,当您拥有命令时:

screen -S VMD54 -X stuff "bash start.sh $(printf \\r)"

What bash does is break it into words removing the quotes (the quotes mark that the whole bash start.sh... thing is one "word"). bash的作用是将其分解为单词,删除引号(引号表示整个bash start.sh...是一个“单词”)。

 screen
 -S
 VMD54
 -X
 stuff
 bash start.sh $(printf \\r)

Then interpret the $ commands inside the separated words 然后在分隔的单词中解释$命令

 screen
 -S
 VMD54
 -X
 stuff
 bash start.sh ␍

It creates a process and passes these six parameters. 它创建一个过程并传递这六个参数。 And you should do exactly the same thing in Java, because Java does not have a bash interpreter built-in. 而且,您应该在Java中做完全相同的事情,因为Java没有内置的bash解释器。 To produce the carriage return character you should just use \\r in Java 要产生回车符,您应该在Java中使用\\r

String[] arguments = { "screen", "-S", code, "-X", "stuff", "bash start.sh \r" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM