Java exec() does not return expected result of pipes' connected commands

后端 未结 6 564
傲寒
傲寒 2020-12-11 05:58

I\'m calling command line programs connected by pipes. All this works on Linux for sure.

My method:

protected String execCommand(String command) thro         


        
6条回答
  •  情歌与酒
    2020-12-11 06:26

    The quick-and-dirty thing to do would be:

    command = "/bin/sh -c '" + command.replaceAll("'", "'\''") + "'"
    

    Normally, you'll have to watch out for shell injection (i.e. someone sneaks "; rm -rf /;" into the command). But that's only an issue if part of the command can be supplied from some other user input.

    The slow and painful approach would be to do the Bash piping yourself in Java. If you go down this road, you'll find out all the wonderful things that Bash gives you that's not directly available from Process.exec (pipes, redirection, compound commands, variable expansion, arithmetic evaluation, ...).

    1. Parse the command for | characters. Be sure to watch out for || and quoted strings.
    2. Spawn a new Process for every piped command.
    3. Create Threads that read the output from one command and write it to the input of the next command.

提交回复
热议问题