如何将参数从包装器 shell 脚本传递到 Java 应用程序?
我想在命令行(linux 和 mac)上运行我创建的 Java 程序。我不想一直输入“java”和参数,所以我正在考虑创建包装脚本。为了让它们在任何地方都能工作,最好的方法是什么?我也希望能够传递论据。我正在考虑使用“shift”来做到这一点(删除第一个参数)。
有没有更好的方法来完全不使用脚本来做到这一点?也许制作一个不需要通过“java”命令调用的可执行文件?
I want to run Java programs I am creating at on the command line (linux and mac). I don't want to type "java" and arguments all the time, so I am thinking about creating wrapper scripts. What's the best way to do this so that they work everywhere? I want to be able to pass arguments, too. I was thinking of using "shift" to do this (removing first argument).
Is there a better way to do this without using scripts at all? Perhaps make an executable that doesn't require invocation through the "java" command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您使用的是与 Bourne shell 兼容的 shell;例如 sh、bash、ksh 等,以下包装器会将所有命令行参数传递给 java 命令:
$@
扩展为 shell 脚本的其余参数,并在其周围加上引号会导致参数要单独加引号,以便以下代码将单个参数传递给 Java:如果包装脚本中的
"$@"
周围没有双引号,Java 将收到上述的三个参数。请注意,这不适用于
"$*"
。根据bash
手册输入:换句话说,所有 shell 参数都将连接到 Java 应用程序的单个命令参数中,忽略原始单词边界。
有关 shell 如何处理引用的更多信息,请参阅 bash 或 sh 手册...或 POSIX shell 规范...。
Assuming that you are using a shell that is compatible with the Bourne shell; e.g. sh, bash, ksh, etc, the following wrapper will pass all command line arguments to the java command:
The
$@
expands to the remaining arguments for the shell script, and putting quotes around it causes the arguments to be individually quoted, so that the following will pass a single argument to Java:Without the double quotes around
"$@"
in the wrapper script, Java would receive three arguments for the above.Note that this does not work with
"$*"
. According to thebash
manual entry:In other words, all shell arguments would be concatenated into a single command argument for your Java application, ignoring the original word boundaries.
Refer to the
bash
orsh
manual ... or the POSIX shell spec ... for more information on how the shell handles quoting.您可以创建一个shell脚本,接受参数。在你的 shell 脚本中,它看起来像这样:-
在这种情况下,
YourApp
接受两个参数。如果您的 shell 脚本名为app.sh
,您可以像这样执行它:-You can create a shell script that accepts arguments. In your shell script, it will look something like this:-
In this case,
YourApp
accepts two arguments. If your shell script is calledapp.sh
, you can execute it like this:-