2

I definitely need to practice my scripting... So far I have the script below which works when one .zip and one flat file are put into the source location. If multiple files are put in it does not execute properly and I am hoping to see if someone can help with a more efficient way. Just to clarify the script needs to scan the source folder for any .zip files, unzip them to a folder of the same name minus the .zip then move new folders to the destination along with any other flat files or non .zip files in the source to a separate location and also delete the original .zip files.

#! /bin/bash

cd "/path/to/source/Location"
for file in $(ls *.zip); do unzip $file -d $(echo $file | cut -d . -f 1); done
mv $(echo $file | cut -d . -f 1) /Destination/for/Unzip
rm *.zip
mv LOCK* /Destination/For/Flat/Files

1 Answer 1

5

You can use for with globbing directly, strip the .zip extension using shell constructs, and extract the archive directly to the destination:

#!/bin/bash

cd "/path/to/source/location"
for file in *.zip; do
  unzip "${file}" -d "/destination/for/unzip/${file%%.zip}" && rm "${file}"
done
mv LOCK* /destination/for/flat/files

This also ensures that archives are only deleted if they were extracted successfully.

8
  • Thank you, this is more efficient then what I had. I am going to test it. Will this work with multiple .zip files in the source folder and multiple flat files?
    – Dave_Z
    Oct 8, 2019 at 15:54
  • Yes, it should. Is there a connection between the archives and the LOCK files? Oct 8, 2019 at 15:59
  • The LOCK files are separate flat files for an application but need to go in a specific location and the way these files are getting transferred they are pretty much just being dumped in the source location with the .zip files that need to be extracted and moved as well. I am getting line 6: syntax error: unexpected end of file error when testing now I think from the mv line
    – Dave_Z
    Oct 8, 2019 at 16:10
  • Oops I just had to move done to the next line after the mv line and its working great so far. Thank you!
    – Dave_Z
    Oct 8, 2019 at 16:15
  • Sorry I think I was commenting at the same time you were last response haha. Should I put the ; done or is it ok to just have done on the line after the mv string?
    – Dave_Z
    Oct 8, 2019 at 16:19

You must log in to answer this question.

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