使用java classpath的环境变量在shell脚本中不起作用

时间:2013-06-30 22:43:11

标签: java shell classpath

我注意到一个问题反复出现:在shell脚本中使用java命令行上的类路径的env var不起作用。

首先,让我们看看做什么工作:在脚本中使用硬编码的类路径如下:(注意:“classpath is”语句在java程序本身内打印)< / p>

steve@mithril:/shared$     java -classpath .:/shared/mysql-connector-java-5.1.25-bin.jar DbPing com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql user password
classpath is .:/shared/mysql-connector-java-5.1.25-bin.jar
Attempting connection to com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql  password
Connecting to user using URL=jdbc:mysql://localhost:3306/mysql
Successfully connected.

并直接在shell 中使用env var

steve@mithril:/shared$ export CP=.:/shared/mysql-connector-java-5.1.25-bin.jar
steve@mithril:/shared$ java -classpath $CP DbPing com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql user password 
classpath is .:/shared/mysql-connector-java-5.1.25-bin.jar
Attempting connection to com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql  password
Connecting to user using URL=jdbc:mysql://localhost:3306/mysql
Successfully connected.

* not *工作原理:在shell脚本中运行与上面相同的命令:

steve@mithril:/shared$ cat dbping.mysql
CP=.:/shared/mysql-connector-java-5.1.25-bin.jar
echo $CP
java -classpath $CP DbPing com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql user password 
#java -classpath .:/shared/mysql-connector-java-5.1.25-bin.jar DbPing com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql user password 

steve@mithril:/shared$  ./dbping.mysql
.:/shared/mysql-connector-java-5.1.25-bin.jar
classpath is .:/shared/mysql-connector-java-5.1.25-bin.jar
Attempting connection to com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/mysql  password
Could not load db driver com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at DbPing.getConnection(DbPing.java:34)
    at DbPing.main(DbPing.java:22)
Exception in thread "main" java.sql.SQLException: com.mysql.jdbc.Driver
    at DbPing.getConnection(DbPing.java:41)
    at DbPing.main(DbPing.java:22)

跟进:该脚本中包含Windows样式换行符。显然\ r \ n破坏了内部环境变量。发现这个使用

  od -cx

。不管怎样,我会对stephen c表示赞赏,因为他的推动让我走上正确的道路寻找解决方案

1 个答案:

答案 0 :(得分:1)

您描述的症状相当令人费解。我看不出问题(脚本看起来正确),但我已经知道如何开始跟踪它。

  1. 从脚本中删除注释掉的行。

  2. 在脚本的开头添加#!/bin/sh行,以确保您实际使用正确的shell来执行它。 (这样做总是一个好主意......即使你认为默认情况下你会获得正确的shell。这可能会改变,具体取决于平台。)

  3. 要弄清楚shell的作用,请在set -vx行之后添加#!/bin/sh

  4. “ - v”表示回显每个脚本行读取,“ - x”表示回显执行的实际命令行。这将告诉您正在运行的命令...以便您可以找出命令参数真正的内容。