Bash: How to check if a zip file contain a specified path/file.ext?
To check for specific file, you can combine unzip -l
with grep
to search for that file. The command will look something like this
unzip -l archive.zip | grep -q name_of_file && echo $?
What this does is it lists all files in archive.zip
, pipes them to grep
which searches for name_of_file
. grep
exits with exit code 0
if it has find a match. -q
silences the output of grep and exits immediatelly with exit code 0
when it finds a match. The echo $?
will print the exit code of grep
. If you want to use it in if statement, your bash script would look like this:
unzip -l archive.zip | grep -q name_of_file;
if [ "$?" == "0" ]
then
...
fi;
on command-line you can try:
$ if [[ `unzip -Z1 audio.zip | grep help.mp3` ]];then echo 'yes';fi
if the help.mp3
is found the output would be yes
see:
help [[
on bash
Most of these methods work as expected, except when the filename has non-standard characters such as newlines. Example:
$ unzip -l foo.zip
Archive: foo.zip
Length Date Time Name
--------- ---------- ----- ----
0 05-06-2020 12:25 foo^Jbar
0 05-06-2020 12:25 foonbar
--------- -------
0 2 files
As you see, the newline character is replaced with ^J
. You could start using this in your grep
, but then you need to know all other Control characters by heart.
The following methods works always:
$ unzip -Z foo.zip foo$'\n'bar &>/dev/null && echo true || echo false
true
$ unzip -l foo.zip foo$'\n'bar &>/dev/null && echo true || echo false
true