简体   繁体   中英

How to use Runtime.exec() with backslash?

I try to start an shell script from a detached screen in java.

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

What is wrong with my code? Nothing happens in the screen VMD54 .

It's better to use ProcessBuilder than 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. 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").

 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. To produce the carriage return character you should just use \\r in Java

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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