Search code examples
bashfor-loopoutputunzip

Unable to mute unzip output in script


I wrote a script that unzips certificates from zips and tests the certs against one of our servers:

#!/bin/bash
WORKINGDIR=$(pwd)
if [ ! -f ./users.zip ]; then
    echo "users.zip not found. Exiting."
    exit 1
        else 
            unzip users.zip -d users
            echo "users.zip extracted."
fi
cd ./users/client

echo "Extracting files..."
for file in `ls *.zip`; do 
    unzip -j $file -d `echo $file | cut -d . -f 1` &> /dev/null
done
echo "name,result" > $WORKINGDIR/results.csv
i=0 # Total counter
j=0 # Working counter
k=0 # Failed counter
for D in `ls -d */`; do
        cd "$D"
        SHORT=`find *.p12 | cut -f1 -d "."`
        openssl pkcs12 -in `echo $SHORT".p12"` -passin file:./password -passout pass:testpass -out `echo $SHORT".pem"` &> /dev/null
        echo "Trying: "$SHORT
        ((i++))
        curl --cert ./`echo $SHORT".pem"`:testpass https://example.com -k &> /dev/null
        OUT=$?
        if [ $OUT -eq 0 ];then
                    ((j++)) ; echo -e $(tput setaf 2)"\t"$SHORT": OK $(tput sgr0)" ; echo $SHORT",OK" >> $WORKINGDIR/results.csv
                else
                    ((k++)) ; echo -e $(tput setaf 1)"\t"$SHORT": FAILED $(tput sgr0)" ; echo $SHORT",FAILED" >> $WORKINGDIR/results.csv
        fi
        rm `echo $SHORT".pem"`
        cd ..
done
echo "Test complete:"
echo "Tested: "$i
echo "Working: "$j
echo "Failed: "$k
echo "Results saved to "$WORKINGDIR"/results.csv"
exit 0

When it gets to the unzipping part I always get this output:

Archive:  users.zip
   creating: users/keys/
  inflating: users/keys/user1.zip
  inflating: users/keys/user2.zip
  inflating: users/keys/user3.zip
  inflating: users/keys/user4.zip
  inflating: users/keys/user5.zip
  inflating: users/keys/user6.zip
  inflating: users/keys/user7.zip
  inflating: users/keys/user8.zip
  inflating: users/keys/user9.zip
  inflating: users/keys/user10.zip
  inflating: users/keys/user11.zip

I've tried to pipe the output to /dev/null in different ways: &> /dev/null 1>&- 2>&- 2>&1 etc. Nothing works. What's weird is that if I put just the unzipping part of the script into a separate script file:

#!/bin/bash
for file in `ls *.zip`; do
        unzip -j $file -d `echo $file | cut -d . -f 1` &> /dev/null
done

It works no problem. Any thought on why this is happening?


Solution

  • I figured it out and feel like quite the simpleton.

    I was getting the output from the first time I call unzip:

    unzip users.zip -d users
    

    and not from the loop:

    for file in `ls *.zip`; do 
        unzip -j $file -d `echo $file | cut -d . -f 1` &> /dev/null
    done
    

    I added -qq to the first unzip:

    unzip -qq users.zip -d users
    

    and it works as expected.