简体   繁体   English

如何为.jar命令行脚本创建别名?

[英]How do I create an alias for a .jar command-line script?

I've got a jar file that can be run from the command line like this: 我有一个jar文件,可以从命令行运行,如下所示:

# In Terminal.app
java -jar fop.jar /path/to/infile.fo /path/to/outfile.pdf

At the moment for this to work I need to navigate to the folder containing fop.jar . 在此工作的那一刻,我需要导航到包含fop.jar的文件夹。 This isn't ideal, so I've tried to add the following alias to bash_profile ... 这不是理想的,所以我尝试将以下别名添加到bash_profile ......

# In bash_profile
alias fop="java -jar /path/to/a/far/away/folder/fop-2.1/build/fop.jar"

...with the hope that I could execute this script from the Desktop (or anywhere else) like so: ...希望我可以从桌面(或其他任何地方)执行此脚本,如下所示:

# In Terminal
fop ~/Desktop/simple.fo ~/Desktop/simple.pdf 

Unfortunately it's not working: 不幸的是它不起作用:

# Error message
Unable to start FOP:
java.lang.RuntimeException: fop.jar not found in directory: /my/pwd (or below)
    at org.apache.fop.cli.Main.getJARList(Main.java:70)
    at org.apache.fop.cli.Main.startFOPWithDynamicClasspath(Main.java:130)
    at org.apache.fop.cli.Main.main(Main.java:219)

Can anyone help? 有人可以帮忙吗?

An alias or a function should work fine as long as the real path of java and fop.jar is used: 只要使用javafop.jar的真实路径,别名或函数就可以正常工作:

$ which java
/usr/bin/java

If you wanted to create a function (which has the benefit of allowing you to change options, parameters, arguments, etc.) you could add something such as this to ~/.bash_profile : 如果你想创建一个函数(它的好处是允许你改变选项,参数,参数等),你可以在~/.bash_profile添加这样的东西:

# fop: run java -jar with input and output files
fop () { /usr/bin/java -jar /path/to/fop.jar "$1" "$2" ; }

The key ingredient is telling the function or alias the path of your java executable and fop.jar . 关键因素是告诉函数或别名java可执行文件和fop.jar的路径。 Another thing that might help resolve the issue is to create a symlink to fop.jar someplace convenient, then you can easily reference it as needed. 另一个可能有助于解决问题的方法是在方便的地方为fop.jar创建一个符号链接,然后您可以根据需要轻松地引用它。

ln -s /path/to/fop.jar /path/to/symlink

So by doing that your command would essentially would become: 所以通过这样做你的命令基本上会变成:

/usr/bin/java -jar /path/to/symlink infile outfile

In Bash, when to alias, when to script, and when to write a function? 在Bash中,何时为别名,何时编写脚本以及何时编写函数?

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

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