I need to check if all the files in 1 jar exist in another jar. I don't care if the file contents are the same, just the file names. I could open each jar in vim and save those text files that are a list of the file names to compare, but I have a lot of jar sets to compare, so I'd like to fully automate this if possible.
-
You're basically asking us to do your work. Hint: `unzip -l
` will list you the content of a jar file. – tink Jan 25 '18 at 19:09 -
Please take your time to read how to [formulate better questions](https://stackoverflow.com/help/mcve) and update yours. – LMC Jan 26 '18 at 01:44
2 Answers
A jar file is built around the ZIP file format and usually contains a manifest file which is a list of all the files that are included in the jar file. This manifest, if it exists, will have the name META-INF/MANIFEST.MF
and it will be a text file.
So what you want may be achieved by extracting the manifest from each jar pair you want to compare and then looking for differences.
If you have the jar
command available, you may extract the manifest of a jar file with:
jar xf jar1.jar META-INF/MANIFEST.MF
You may also do this with unzip
if you have it available.
A simple script that would extract the manifests from two jar files and compare them using diff
would look like:
#!/usr/bin/env bash
jar xf "$1" META-INF/MANIFEST.MF
mv META-INF/MANIFEST.MF m1.txt
jar xf "$2" META-INF/MANIFEST.MF
mv META-INF/MANIFEST.MF m2.txt
diff m1.txt m2.txt
The script takes two parameters, the jar files. If you expect the files in the manifests to be the same but in different order, you may try sorting them first with sort
. This is only the skeleton of a script. You may want to add things like file cleanup, error checking and so on.
If you only care about the files inside the jar files, you may get a list of them with:
jar tf jar1.jar
You may also use unzip
for this: unzip -l jar1.jar
as suggested in a comment.
Then you may compare the list of files with diff
in a similar fashion, maybe sorting them with sort
first.
There is also a related question: How to read MANIFEST.MF file from JAR using Bash.

- 2,066
- 1
- 16
- 25
-
Play with the results of the `diff`. If I am not mistaken, given two ordered lists of files `l1` and `l2`, `diff l1 l2 | egrep '^<' | wc -l` should give you `0` if `l1` is contained in `l2` and greater than zero otherwise. – Javier Elices Jan 26 '18 at 08:00
-
unzip -l, combined with awk, sort, and comm, worked for me. I didn't know about unzip -l, thanks. – Thundercleez Jan 26 '18 at 13:26
"I need to check if"...so do you need the script to exit true/false or to output a list of files in first but not second jar? For the latter case this will do:
#!/bin/bash
(jar tf "$1";jar tf "$2";jar tf "$2") | \
sort | uniq -c | perl -pe's/^\s*([23]\s+.*\n|1\s+)//'
Store this in files_just_in_first_jar
and run chmod +x files_just_in_first_jar
and test with:
./files_just_in_first_jar bundle1.jar bundle2.jar

- 3,468
- 20
- 22