Using Quotes within getRuntime().exec

前端 未结 6 806
不思量自难忘°
不思量自难忘° 2020-11-30 06:46

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

6条回答
  •  粉色の甜心
    2020-11-30 07:03

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

提交回复
热议问题