Note here, .zip and .jar is just an example, my file extensions are different. Suppose I have a directory which can contain number of zip files

a.zip b.zip c.zip


z.jar x.jar y.jar

along with other contents.

I want to unzip them all.

I tried

unzip -q *.zip


unzip -q *.jar

But when the folder does not contain .jar files, the second command would fail

unzip:  cannot find or open *.jar, *.jar.zip or *.jar.ZIP.

No zipfiles found.

This is problematic for me as it an error my script would exit. I want to silently unzip the *.zip and *.jar without errors. Is there anyway to accomplish this?

1 Answer 1


Yes, you can use nullglob in bash:

$ shopt -s nullglob
$ tee foo.zip bar.zip </dev/null
$ echo *.zip *.jar
bar.zip foo.zip

The nullglob option changes the behaviour of a non-matching glob from becoming a literal string to being removed entirely.

However, this will likely not suffice in your particular use case, as unzip won't know what to do if it is passed no arguments. You should check if there are zips/jars to unzip first, like so:

shopt -s nullglob
zips=( *.zip )
jars=( *.jar )
(( "${#zips[@]}" )) && unzip -q "${zips[@]}"
(( "${#jars[@]}" )) && unzip -q "${jars[@]}"

Or all at once (if applicable):

shopt -s nullglob
zipsandjars=( *.zip *.jar )
(( "${#zipsandjars[@]}" )) && unzip -q "${zipsandjars[@]}"

In POSIX shell something similar can also be done like so:

for file in *.zip *.jar; do
    if [ "$file" != "*.zip" ] && [ "$file" != "*.jar" ]; then
        unzip -q "$file"
  • This one still gave, jars were not found. when my directory did not have .jars Nov 9, 2012 at 2:43
  • Okay, I had not set the shopt -s nullglob I guess that is the key. Nov 9, 2012 at 2:44
  • great solution. Why does ${#zipsandjars[@]} have to be surrounded with quotes?
    – iruvar
    Nov 9, 2012 at 3:02
  • @ChandraRavoori It doesn't, it's just good practise to always quote your expansions.
    – Chris Down
    Nov 9, 2012 at 3:06
  • yes, where the possibility of embedded whitespace exists. in this specific case would not ${#zipsandjars[@]} always resolve to a number?
    – iruvar
    Nov 9, 2012 at 3:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .