我试图在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();
}
如果外壳需要用户输入,我该如何给用户输入?
如何实现呢?
例如:my_script.sh
#!/bin/bash
read -p "Enter your name : " name
echo "Hi, $name. Let us be friends!"
我需要通过Java输入名称。
最佳答案
编辑以下评论
// 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 );
和发球台输出可能是从外壳完成
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的问题,不应捕获它并继续执行程序,而应传播到任务真正完成为止。
关于java - 执行使用Java执行期间需要输入内容的Shell脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49108741/