Shell script to find a class in a set of Jar files

When you work on a Java project with many library dependencies it can be difficult to know which Jar files contain which classes. Hunting down a particular class in a tangled mess of Jar files can be painful, especially if you need to do so on a server over a shell connection.

Here is a handy shell script that iterates over all the Jar archives in a given path, finds those containing file names that match a given pattern, and prints out these matches followed by the name of the Jar file.

#!/bin/sh

if [ -z "$2" ]
then
  echo Usage: $0 Directory ClassName
  exit 1
fi

for f in $(find $1 -name '*.jar')
do
  jar tf $f | grep "$2" && echo "[in $f]"
done

Save this script to a file with an obvious name, like findInJars.sh.

To find all the classes with names containing “HttpClient” in the libs directory, you would invoke the script like so:

$ sh findInJars.sh libs HttpClient

org/apache/commons/httpclient/HttpClient.class
org/apache/commons/httpclient/HttpClientError.class
org/apache/commons/httpclient/params/HttpClientParams.class
[in libs/commons-httpclient/commons-httpclient-3.1.jar]

If you are impatient, you can accomplish the same thing with a big and ugly one-liner:

for f in $(find <b>libs</b> -name '*.jar'); do jar tf $f | grep <b>HttpClient</b> && echo "[in $f]"; done
This entry was posted in Coding. Bookmark the permalink.

2 Responses to Shell script to find a class in a set of Jar files

  1. Andre Cesta says:

    Script will break with file paths containing spaces.

  2. James Murty says:

    If you need to search file paths that contain spaces, you can restructure the for-loop portion of the script.

    Change this portion:

    for f in $(find $1 -name '*.jar')
    do
      jar tf $f | grep "$2" && echo "[in $f]"
    done

    To this:

    find $1 -name '*.jar' | while read f
    do
      jar tf "$f" | grep "$2" && echo "[in $f]"
    done

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>