1

I have the following script which does close to what I need; that is, to search the whole system for jar files that contain a specific java class file. My only issue with this script is getting it to acknowledge when it has found a class file in the jar based on the class name I pass in. The script at the moment only gives me back the class package inside the jar, not the jar it is in, which means its kind of useless. I'm trying to use $? to check if the search command was successful and if so echo the directory it was in into a file. It's always returning success(0) though, so every jar location it finds it is appending to the file. I'll stop talking now, can someone run this script and see what it is doing vs what I am trying to do?

if [ $# -ne 1 ]
then
   echo "Need to provide class name as argument"
   exit 1
fi

> findClassResults.txt

for i in $(locate "*.jar");
do
    if [ -d $i  ]
    then
        continue
    fi

    if jar -tvf $i | grep -Hsi $1.class 1>/dev/null
    then
        potentialMatches=`jar -tvf $i | grep -Hsi $1.class`
        exactMatch=`echo $potentialMatches | grep -o \/$1.class`
        if [ ! -z $exactMatch ]
        then
            echo "matches found: " $potentialMatches >> findClassResults.txt
            echo ".....in jar @: " $i >> findClassResults.txt
            echo -e "\n" >> findClassResults.txt
        fi
    fi
done

Edit: the above is now the working script. It will find any .class file and the location of its jar on the system by passing in the name of the class e.g. ./findClass.sh MyClass

Alan Smith
  • 1,069
  • 4
  • 19
  • 23

2 Answers2

1

Redirect the output of the loop as a whole to your results file, not each command individually (and use a while loop to iterate over the results, not a for loop):

< <(locate "*.jar") while read -r i
    do
        if [ -d "$i"  ] #mvn repos have dirs named as .jar, so skip...
        then
           continue
        fi
        if jar -tvf "$i" | grep -q -Hsi "$1.class"
        then
          echo "jar location: $i"
        fi
done | tee -a findClassResutls.txt
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Hi, thanks. I did a slight variation of what you have above and I have it working now. I'll update my post with my script. Cheers. – Alan Smith May 07 '15 at 10:02
0

the $? you're using there is on the tee command, which I bet pretty well always succeeds. You probably want Pipe output and capture exit status in Bash

Community
  • 1
  • 1
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67