Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding jars from dynamically generated classpaths?

Tags:

java

bash

I'm launching my java server from a bash script. The server has "provided" dependencies on 3rd party jars. However, some of those jars conflict with jars in my app, and need to be excluded from the classpath...

At the moment, I only need to exclude one jar, so this idiom gets me by

EXTERNAL_JARS=$(find "${EXTERNAL_LIB}" -name 'slf4j-log4j12-1.4.3.jar' -prune -o -type f -name '*.jar' -printf ':%p' )
CLASSPATH=${CLASSPATH}${EXTERNAL_JARS}

Is there a better approach to use when the number of external jars is 20-30 and the number of excluded jars is ~ 5 ?

like image 605
VoiceOfUnreason Avatar asked Aug 30 '26 12:08

VoiceOfUnreason


1 Answers

This would work, although it assumes that you don't have spaces in your filenames.

EXCLUDED="slf4j-log4j12-1.4.3.jar
some-other-library.jar
something-else.jar"

EXTERNAL_JARS=$(
  find "${EXTERNAL_LIB}" -type f -name '*.jar' \
    | grep -v -F"$EXCLUDED" \
    | xargs \
    | tr ' ' ':'
)

CLASSPATH=${CLASSPATH}:${EXTERNAL_JARS}

The idea here is to use grep -v -F and a multi-line string variable to filter out the excluded jars.

When you do that, you can no longer use the -printf flag in find, so you replace it with xargs | tr ' ' '-'. Here xargs will concatenate all the jars, separating them with a space and the tr command replaces those spaces with colons. Again, this will work if you don't have spaces in your path.

like image 123
carl.anderson Avatar answered Sep 01 '26 00:09

carl.anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!