简体   繁体   English

如何制作Java Shell命令(不使用Java运行Shell命令)

[英]How to make a Java Shell Command (NOT how to run a shell command with Java)

I just finished an terminal program and cannot figure out how I can properly deploy it so it can be executed as such via bash: 我刚刚完成了一个终端程序,无法弄清楚如何正确部署它,因此可以通过bash这样执行它:

myjavaprogram [options]

At best, I can only seem to get 充其量我似乎只能得到

java -jar /path/to/myjavaprogram [options]

to work. 上班。 But this is insufficient. 但这还不够。 I'd like to give the program a clear name that I can quickly type. 我想给程序起一个清晰的名字,我可以快速输入。 And before you say it, yes, I tried making a shell command already. 在您说出来之前,是的,我已经尝试过执行Shell命令。 It went as follows, and I named it what I wanted to name it: 结果如下,我将其命名为我想命名的名称:

#!/bin/bash
java -jar /path/to/myjavaprogram

I saved it to /usr/bin along with the other commands. 我将其与其他命令一起保存到了/ usr / bin。

Problem is when I tried to run it, it wouldn't allow me to input options. 问题是当我尝试运行它时,它不允许我输入选项。 Any advice from any java folks who have deployed a terminal application before? 从以前部署过终端应用程序的任何Java人员那里得到什么建议? I don't want to have to type out the full path name each time I run the thing, as it is to be used for a very high volume purpose (lots of data crunching etc.). 我不想每次运行事物时都必须输入完整的路径名,因为它用于大量用途(大量数据处理等)。 Any advice is appreciated. 任何建议表示赞赏。 Thanks. 谢谢。

Sorry. 抱歉。 HTML screwup there. HTML搞砸了。 I meant to say I want it to run like "myjavaprogram [options]" I used angle brackets accidentally. 我的意思是说我希望它像“ myjavaprogram [options]”一样运行,我不小心使用了尖括号。

If you want aa Bash solution, look into bash command line arguments. 如果您需要Bash解决方案,请查看bash命令行参数。 Generally you would use $1, $2, $3 etc to specify options, so in your case, if you want 3 options you would write this. 通常,您将使用$ 1,$ 2,$ 3等来指定选项,因此,在您的情况下,如果需要3个选项,则可以编写此选项。

java -jar /path/to/myjavaprogram $1 $2 $3

and run it like so 像这样运行

my_prog 1 2 3

If you want to tell bash to process any other command line options given, use $@ 如果要告诉bash处理给定的任何其他命令行选项,请使用$ @

java -jar /path/to/myjavaprogram $@

and run it liks so 并运行它,所以

my_proc 1 2 3 4 5 6 7 8 9 10

This should work 这应该工作

#! /bin/bash
exec java -jar /path/to/myjavaprogram "$@"

Notice the use of exec to discard bash and the quotes surrounding $@ to preserve whitespaces. 注意,使用exec丢弃bash$@周围的引号以保留空格。

EDIT 编辑

Try this as your java program 试试这个作为您的Java程序

public class T1 {
    public static void main(String args[]) {
        System.out.println(java.util.Arrays.toString(args));
    }
}

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

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