如何将参数传递给jshell脚本? [英] How to pass arguments to a jshell script?
问题描述
我愿意将参数传递给jshell脚本.例如,我会喜欢这样的东西:
I am willing to pass arguments to a jshell script. For instance, I would have liked something like this:
jshell myscript.jsh "some text"
,然后在脚本中的某些变量中提供字符串"some text".
and then to have the string "some text" available in some variable inside the script.
但是,jshell
只需要一个文件列表,因此答案是:
However, jshell
only expects a list of files, therefore the answer is:
File 'some text' for 'jshell' is not found.
有什么方法可以正确地将参数传递给jshell脚本吗?
Is there any way to properly pass arguments to a jshell script?
到目前为止,我唯一的解决方案是在调用脚本时使用环境变量:
My only solution so far is to use an environment variable when calling the script:
ARG="some test" jshell myscript.jsh
然后我可以使用以下脚本在脚本中访问它:
And then I can access it in the script with:
System.getenv().get("ARG")
推荐答案
选项-R
> jshell -v -R-Da=b ./file.jsh
用于脚本
{
String value = System.getProperty("a");
System.out.println("a="+value);
}
/exit
会给你
> jshell -v -R-Da=b ./file.jsh
a=b
另一种方式是:
{
class A {
public void main(String args[])
{
for(String arg : args) {
System.out.println(arg);
}
}
}
new A().main(System.getProperty("args").split(" "));
}
和执行
> jshell -R-Dargs="aaa bbb ccc" ./file_2.jsh
更新
Update
先前的解决方案将因更复杂的参数而失败.例如. 'This is my arg'
.
Previous solution will fail with more complex args. E.g. 'This is my arg'
.
但是我们可以从ant
中受益,它是CommandLine
类
But we can benefit from ant
and it's CommandLine
class
import org.apache.tools.ant.types.Commandline;
{
class A {
public void main(String args[])
{
for(String arg : args) {
System.out.println(arg);
}
}
}
new A().main(Commandline.translateCommandline(System.getProperty("args")));
}
然后,我们可以这样称呼它:
and then, we can call it like this:
jshell --class-path ./ant.jar -R-Dargs="aaa 'Some args with spaces' bbb ccc" ./file_2.jsh
aaa
Some args with spaces
bbb
ccc
当然,ant.jar
必须位于通过--class-path
这篇关于如何将参数传递给jshell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!