执行在使用Java执行期间获取输入的shell脚本

问题描述 投票:1回答:2

我试图在Java中执行shell脚本。我能够通过以下方式实现这一目标。

        ProcessBuilder pb = new ProcessBuilder("/path_to/my_script.sh");
        pb.redirectOutput(new File("/new_path/out.txt"));
        Process p = pb.start();
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

如果shell需要用户输入,我将如何提供用户输入?怎么实现这个?

示例:my_script.sh

#!/bin/bash
read -p "Enter your name : " name
echo "Hi, $name. Let us be friends!"

我需要通过Java输入名称。

java bash shell
2个回答
1
投票

编辑后评论

    // writing to file
    String input = "Bob";
    try ( PrintWriter out = new PrintWriter( filename ) ) {
        out.print( input );
    }

    // redirecting input from file
    pb.redirectInput( new File( filename ) );
    pb.redirectOutput( Redirect.INHERIT );

初步答复;

根据它的发射方式,以下可能就足够了

pb.redirectInput( Redirect.INHERIT );

但是要查看消息,还应将输出重定向到std out

pb.redirectOutput( Redirect.INHERIT );

和tee输出可能是从shell完成的

exec 6>&1 1> >(tee /new_path/out.txt)  # start tee output to out.txt (save current output to file descriptor 6 for example)
...
exec >&6      # end to restore standard output and terminate tee process

关于InterruptedException的注意事项,它不应该被捕获并继续该程序,而是传播到任务真正完成的点。


0
投票

嗨你可以这样做: -

 String inputName = "blabla";
 String command = "/path_to/my_script.sh  " + inputName;
 Process p;
 try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

现在你必须修改你的shell脚本,如下所示: -

#!/bin/bash
#read -p "Enter your name : " name
name = $1
echo "Hi, $name. Let us be friends!"
© www.soinside.com 2019 - 2024. All rights reserved.