This will be a really simple freebie for a bash guru:
Question
Using bash, how do you make a classpath out of all files in a directory?
Details
Given a directory:
LIB=/path/to/project/dir/lib
that contains nothing but *.jar files such as:
junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
I need to create a colon-separated classpath variable in the form:
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
Some seudo-code that nearly expresses the logic I’m looking for would be along the lines of:
for( each file in directory ) {
classpath = classpath + ":" + LIB + file.name
}
What is a simple way to accomplish this via bash script?
New Answer
(October 2012)
There’s no need to manually build the classpath list. Java supports a convenient wildcard syntax for directories containing jar files.
(Notice that the
*is inside the quotes.)Explanation from
man java:Old Answer
Good
Simple but not perfect solution:
There’s a slight flaw in that this will not handle file names with spaces correctly. If that matters try this slightly more complicated version:
Better
This only works if your find command supports
-printf(as GNUfinddoes).If you don’t have GNU
find, as on Mac OS X, you can usexargsinstead:Best?
Another (weirder) way to do it is to change the field separator variable
$IFS. This is very strange-looking but will behave well with all file names and uses only shell built-ins.Explanation:
JARSis set to an array of file names.IFSis changed to:.$IFSis used as the separator between array entries. Meaning the file names are printed with colons between them.All of this is done in a sub-shell so the change to
$IFSisn’t permanent (which would be baaaad).