How to pass arguments from wrapper shell script to Java application?

社会主义新天地 提交于 2020-01-09 19:19:08

问题


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?


回答1:


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:

#!/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:

$ 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.


Note that this does not work with "$*". According to the bash manual entry:

"$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable.

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 or sh manual ... or the POSIX shell spec ... for more information on how the shell handles quoting.




回答2:


You can create a shell script that accepts arguments. In your shell script, it will look something like this:-

java YourApp $1 $2

In this case, YourApp accepts two arguments. If your shell script is called app.sh, you can execute it like this:-

./app.sh FirstArgument SecondArgument 


来源:https://stackoverflow.com/questions/4771755/how-to-pass-arguments-from-wrapper-shell-script-to-java-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!