执行shell脚本与从Java参数 [英] Executing shell-script with parameters from java
问题描述
我一直在谷歌上搜索了一段时间,大家似乎有不同的解决方案,其中没有一个似乎是为我工作。
I have been googling for some time, and everyone seems to have a different solution, none of which appear to be working for me.
我已经试过这两个的ProcessBuilder
和运行
。无论调用 .SH
文件中直接和其送入 /斌/庆典
。没有运气。
I have tried both ProcessBuilder
and Runtime
. Both calling the .sh
file directly and feeding it to /bin/bash
. With no luck.
回到基础,我目前的code是如下:
Back to basics, my current code is as follows;
String cmd[] = { "~/path/to/shellscript.sh", "foo", "bar" };
Process p = Runtime.getRuntime().exec(cmd);
这是给没有这样的文件或目录
的错误,尽管手动运行;
Which is giving a No such file or directory
error, despite that manually running;
~/path/to/shellscript.sh foo bar
这是bash的完美作品。
Works perfectly from bash.
我需要保持〜
因为这个shellscript里存在在三个不同的用户略有不同的形式。
I need to keep the ~
because this shellscript exists in slightly different forms for three different users.
推荐答案
一个选项是处理〜
自己:
String homeDir = System.getenv("HOME");
String[] cmd = { homeDir + "/path/to/shellscript.sh", "foo", "bar" };
Process p = Runtime.getRuntime().exec(cmd);
另一种方法是让猛砸为您处理:
Another is to let Bash handle it for you:
String[] cmd = { "bash", "-c", "~/path/to/shellscript.sh foo bar" };
Process p = Runtime.getRuntime().exec(cmd);
这篇关于执行shell脚本与从Java参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!