Wednesday, June 27, 2007

jwhich - Java classes can run but they can no longer hide

This bash command will search all .jar files in the current directory and all subdirectories for MyClass:
for f in `find . -name '*.jar'`; do jar tf $f | grep "MyClass" | xargs -n 1 echo "$f:"; done
Here is a complete shell script version that accepts a search argument, optionally followed by a start path. I keep this script at /usr/bin/jwhich on my box.
Sample output:
$ jwhich MyClass
./myapp/my/hard/to/find/subdirectory/mymissing.jar: com/Missing/MyClass.class
$
The script itself:
#!/bin/bash

whichclass=$1
path=$2

if [ -z $whichclass ]; then
echo "usage: $0 searchstring [path]"
echo "\tsearchstring - search for class names that contain this substring"
echo "\tpath (optional) - start at this path (default: current directory)"
echo "\nSearch for a Java Class, scanning all .jar files in the current directory and all subdirectories"
exit 1;
fi

if [ -z $path ]; then
path="."
fi

for f in `find $path -name '*.jar'`; do
jar tf $f | grep $whichclass | xargs -n 1 -r echo "$f:";
done


No comments: