How-to find a class in a JAR directory using shell scripting

This post war originally published here.

The biggest problems in J2EE applications deployment come often from classloader hierarchies and potential overlapping between server-provided and application-specific libraries. So, searching classes through collection of JARs is oftwen the main activity in order to identifiy and fix classloader issues.
This is surely a tedious and repetitive task: so, here’s a shell script you can use to automate JAR collection traversing and tar command’s output analysis to search a pattern, which is provided as script parameter.

Credits: Thanks to sirowain for parameter check and return code related contributions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/bin/bash
# Commonly available under GPL 3 license
# Copyleft Pietro Martinelli - javapeanuts.blogspot.com
if [ -z $1 ]
then
echo "Usage: $0 <pattern>"
echo "tar xf's output will be tested against provided <pattern> in order to select matching JARs"
exit 1
else
jarsFound=""
for file in $(find . -name "*.jar"); do
echo "Processing file ${file} ..."
out=$(jar tf ${file} | grep ${1})
if [ "${out}" != "" ]
then
echo " Found '${1}' in JAR file ${file}"
jarsFound="${jarsFound} ${file}"
fi
done
echo "${jarsFound}"

echo ""
echo "Search result:"
echo ""

if [ "${jarsFound}" != "" ]
then
echo "${1} found in"
for file in ${jarsFound}
do
echo "- ${file}"
done
else
echo "${1} not found"
fi
exit 0
fi

This script is available on github.com:
https://github.com/pietrom/javapeanuts-shell-utils/blob/master/find-jar.sh