Search code examples
shellcentosgunzip

About: extracting *.gz files and move a original file to other folder


I am almost new on shell script but don't know some commands. I am trying to write below shell script , please give some direction. 1. Read *.gz files from specific directory 2. Extract it to other folder 3. Move a original file to another folder. i can do it three separate shell scripts but i want it include one shell script. Then this script will be cronjob and will run every 5 minutes. i was trying to start like below but somehow i am bit confused how to get filelist. I can do here another script but want to include in one script."


#!/bin/bash

while IFS= read file; do
    gzip -c "$file" > "zipdir/$(basename "$file").gz"
done < filelist
-----------------------------------------

PS: Files are created in every 5 minutes.


Solution

  • There are several ways to implement what you're looking for (I would consider notify). Anyhow... this is a very simple implementation:

    $ source=~/tmp/source   # directory where .gz files will be created
    $ target=~/tmp/target   # target directory for uncompressed files
    $ archive=~/tmp/archive # archive dir for .gz files
    $ shopt -s nullglob     # avoid retiring unexpanded paths
    $ for gz in ${source}/*.gz ; do gzip -dc "$gz" > ${target}/$(basename "$gz" .gz) ; mv "$gz" ${archive}/ ; done
    $ shopt -u nullglob     # reset nullglob
    

    If you know for sure "source" directory will always contain .gz files you can avoid shopt.

    Another solution (not requiring shopt) is this:

    find ${source} -name '*.gz' -print0 | while read -d '' -r gz; do
        gzip -dc "$gz" > ${target}/$(basename "$gz" .gz)
        mv "$gz" ${archive}/
    done
    

    The first line looks a little bit complicated because it manages source file names containing spaces...