Bash - 通过搜索整个系统

时间:2015-05-06 13:54:50

标签: java bash unix jar

我有以下脚本,它接近我需要的;也就是说,在整个系统中搜索包含特定java类文件的jar文件。我对这个脚本的唯一问题就是让它在基于我传入的类名在jar中找到一个类文件时确认它。此时脚本只返回jar中的类包,而不是jar它是的,这意味着它没用。我试图用$?检查搜索命令是否成功,如果是,则将其所在的目录回显到文件中。它总是返回成功(0),因此它找到的每个jar位置都附加到文件中。我现在不再说话,有人可以运行这个脚本,看看它在做什么和我想要做什么?

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

编辑:以上是现在的工作脚本。它将通过传入类的名称来查找任何.class文件及其jar在系统上的位置,例如./findClass.sh MyClass

2 个答案:

答案 0 :(得分:1)

将循环的输出作为一个整体重定向到结果文件,而不是单独的每个命令(并使用while循环迭代结果,而不是for循环):

< <(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

答案 1 :(得分:0)

$?$?你正在使用那里的三通命令,我敢打赌总是成功。您可能需要Pipe output and capture exit status in Bash