gpt4 book ai didi

java - 使用 bash,如何从目录中的所有文件中创建类路径?

转载 作者:IT老高 更新时间:2023-10-28 13:54:01 24 4
gpt4 key购买 nike

这将是一个真的简单的 bash 大师免费赠品:

问题

使用 bash,如何从目录中的所有文件中创建类路径?


详情

给定一个目录:

LIB=/path/to/project/dir/lib

只包含 *.jar 文件,例如:

junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar

我需要创建一个以冒号分隔的类路径变量,格式如下:

CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar

几乎可以表达我正在寻找的逻辑的一些伪代码将类似于:

for( each file in directory ) {
classpath = classpath + ":" + LIB + file.name
}

通过 bash 脚本完成此操作的简单方法是什么?

最佳答案

新答案
(2012 年 10 月)

无需手动构建类路径列表。 Java 支持对包含 jar 文件的目录使用方便的通配符语法。

java -cp "$LIB/*"

(注意 *inside 引号。)

来自man java的解释:

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started — no Java program will ever see unexpanded wildcards except by querying the environment.


旧答案

简单但不完美的解决方案:

CLASSPATH=$(echo "$LIB"/*.jar | tr ' ' ':')

有一个小缺陷,它不能正确处理带空格的文件名。如果这很重要,请尝试这个稍微复杂一点的版本:

更好

CLASSPATH=$(find "$LIB" -name '*.jar' -printf '%p:' | sed 's/:$//')

这只有在你的 find 命令支持 -printf 时才有效(就像 GNU find 一样)。

如果你没有 GNU find,就像在 Mac OS X 上一样,你可以使用 xargs 代替:

CLASSPATH=$(find "." -name '*.jar' | xargs echo | tr ' ' ':')

最好的?

另一种(更奇怪的)方法是更改​​字段分隔变量$IFS。这看起来很奇怪,但对所有文件名都表现良好,并且只使用 shell 内置函数。

CLASSPATH=$(JARS=("$LIB"/*.jar); IFS=:; echo "${JARS[*]}")

解释:

  1. JARS 设置为文件名数组。
  2. IFS 改为 :
  3. 回显数组,$IFS 用作数组条目之间的分隔符。这意味着文件名之间用冒号打印。

所有这些都在一个子 shell 中完成,因此对 $IFS 的更改不是永久性的(这将是 baaaad)。

关于java - 使用 bash,如何从目录中的所有文件中创建类路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com