简体   繁体   English

如何将包装shell脚本中的参数传递给Java应用程序?

[英]How to pass arguments from wrapper shell script to Java application?

I want to run Java programs I am creating at on the command line (linux and mac). 我想在命令行(linux和mac)上运行我正在创建的Java程序。 I don't want to type "java" and arguments all the time, so I am thinking about creating wrapper scripts. 我不想一直输入“java”和参数,所以我在考虑创建包装器脚本。 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). 我正在考虑使用“shift”来做到这一点(删除第一个参数)。

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? 也许制作一个不需要通过“java”命令调用的可执行文件?

Assuming that you are using a shell that is compatible with the Bourne shell; 假设您使用的是与Bourne shell兼容的shell; eg sh, bash, ksh, etc, the following wrapper will pass all command line arguments to the java command: 例如sh,bash,ksh等,以下包装器将所有命令行参数传递给java命令:

#!/bin/sh
OPTS=... 
java $OPTS com.example.YourApp "$@"

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: $@扩展为shell脚本的其余参数,并在其周围加上引号会导致参数被单独引用,以便以下内容将单个参数传递给Java:

$ wrapper "/home/person/Stupid Directory Name/foo.txt" 

Without the double quotes around "$@" in the wrapper script, Java would receive three arguments for the above. 如果在包装器脚本中没有"$@"附近的双引号,Java将收到上述三个参数。


Note that this does not work with "$*" . 请注意,这不适用于"$*" According to the bash manual entry: 根据bash手册条目:

"$*" is equivalent to "$1c$2c..." , where c is the first character of the value of the IFS variable. "$*"相当于"$1c$2c..." ,其中cIFS变量值的第一个字符。

In other words, all shell arguments would be concatenated into a single command argument for your Java application, ignoring the original word boundaries. 换句话说,所有shell参数将连接成Java应用程序的单个命令参数,忽略原始单词边界。

Refer to the bash or sh manual ... or the POSIX shell spec ... for more information on how the shell handles quoting. 有关shell如何处理引用的更多信息,请参阅bashsh手册...或POSIX shell规范....

You can create a shell script that accepts arguments . 您可以创建一个 接受参数 的shell脚本 In your shell script, it will look something like this:- 在你的shell脚本中,它看起来像这样: -

java YourApp $1 $2

In this case, YourApp accepts two arguments. 在这种情况下, YourApp接受两个参数。 If your shell script is called app.sh , you can execute it like this:- 如果您的shell脚本名为app.sh ,您可以像这样执行: -

./app.sh FirstArgument SecondArgument 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM