我的 Bash 脚本有问题
他所有人, 我的 bash 脚本有问题。 这是我的代码:
#!/bin/bash
java -jar my_app.jar
echo "The present working directory is `pwd`"
如果我通过 ./script_name 执行它,它就可以工作,但是如果我双击它就不起作用,我收到此错误:
“无法访问 jarfile my_app.jar”。
然后 pwd 输出就不同了!!!
我的操作系统是 MacOSX,但我需要创建一个也可以在 Linux 中运行的 bash 脚本。
He all,
i have a problem with my bash script.
That's my code:
#!/bin/bash
java -jar my_app.jar
echo "The present working directory is `pwd`"
If i exec it by ./script_name it work, but if i double click on it don't work, i got this error:
"Unable to access jarfile my_app.jar".
Then the pwd output is different !!!
My OS is MacOSX but i need to create a bash script that work in Linux too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信解决方案建议的Shawn J. Goff 并由 评论Gordon Davisson 可以通过采用现代 bash 命令替换语法来改进。我假设脚本和 jar 位于同一文件夹中:
I believe the solution suggested by Shawn J. Goff and commented on by Gordon Davisson can be improved by employing modern
bash
command substitution syntax. I'm assuming the script and jar are in the same folder:如果使用图形工具执行脚本,当前工作目录是任意的。当前工作目录在图形应用程序中不是一个有用的概念,并且它们通常不使用或更改它。这意味着您必须在对
java
程序的调用中包含完整路径,或者更改为脚本所在的目录。不幸的是,对于后者没有好的解决方案。If you use a graphical tool to execute the script, the current working directory is arbitrary. The current working directory is not a useful concept in graphical applications, and they usually don't use or change it. This means you must include the full path in the call to the
java
program, or change to the directory where the script is located. Unfortunately, there is no good solution for the latter.变量 $0 应保存脚本的路径。您可以使用 dirname 来获取脚本所在的目录。
The variable $0 should hold the path to the script. You can use dirname to get the directory that the script is in.
好的,所以有两个问题必须解决:
假设您的脚本和 jar 始终安装在同一目录中,问题 1 是识别该目录。 此处对此进行了讨论。一旦您知道了脚本的目录,您就可以引用与之相关的 jar 文件。
系统安装的
java
可执行文件的路径。最终,仅使用裸java
是简单且传统的,并且依赖于正确配置的 PATH。如果这不适合您,只需包含最常见路径的有序列表,然后使用if [ -e /usr/bin/java ]
查看它们是否可执行,例如,运行您的代码找到的第一个。OK, so there are 2 issues you must solve:
Assuming your script and your jar are always installed in the same directory, problem 1 is to identify that directory. That is discussed here. Once you know the script's directory, you can reference your jar file relative to that.
Path to the system's installed
java
executable. Ultimately just using barejava
is straightforward and conventional and relies on the PATH being properly configured. If that doesn't do it for you, just include an ordered list of the most common paths and see if they are executable usingif [ -e /usr/bin/java ]
, for example, running the first one your code finds.