Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

AND/OR

z.jar x.jar y.jar

along with other contents.

I want to unzip them all.

I tried

unzip -q *.zip

and

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?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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"
    fi
done
share|improve this answer
    
This one still gave, jars were not found. when my directory did not have .jars –  Senthil Kumaran Nov 9 '12 at 2:43
    
Okay, I had not set the shopt -s nullglob I guess that is the key. –  Senthil Kumaran Nov 9 '12 at 2:44
    
great solution. Why does ${#zipsandjars[@]} have to be surrounded with quotes? –  1_CR Nov 9 '12 at 3:02
    
@ChandraRavoori It doesn't, it's just good practise to always quote your expansions. –  Chris Down Nov 9 '12 at 3:06
    
yes, where the possibility of embedded whitespace exists. in this specific case would not ${#zipsandjars[@]} always resolve to a number? –  1_CR Nov 9 '12 at 3:18
show 3 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.