0

I am writing a scriptwhere in a file there are .zip files and .tar.gz files. I have to extract the files. I know how to use tar for tar.gz and unzip for zip files but don't know how to take decision based on extensions. I have written a script which works for tar.gz. Here is the script.

#!/bin/bash
echo "Evaluate Lab"
select yn in "Yes" "No";
do
    case $yn in
    Yes )
        echo "Evaluating!!"
        #choose file
        file="$(ls | head -1)"
        echo $file

        mkdir temp
        echo "Decompressing file $file"
        #Decompress chosen tar.gz to temp
        tar -xf "$file" --directory temp

        cd temp/
        #Do some work here
        #get out of temp folder
        cd ../
        rm -rf temp
        echo "Moving $file to done"
        mv "$file" ../done/
        echo "Evaluate another"
        echo "1) Yes     2) No"
        ;;
    No )
        echo "Exiting...."
        exit;;
    *)
        echo "Enter right option";;
    esac
done

I've to work on both tar.gz and zip. Any hints?

  • 1
    Your ls | head -1 is poor practise. If you care to share a little more of your script we might be able to make suggestions on that too. – roaima Nov 11 '18 at 9:04
  • @roaima I've modified the description and added the partial script written by me. – LearningGiraffe Nov 11 '18 at 9:21
  • How do you know that the tar.gz file that you are interested in is the first file returned by ls? – Kusalananda Nov 11 '18 at 9:33
  • @Kusalananda The file only contains compressed files. I'm assuming it is tar. – LearningGiraffe Nov 11 '18 at 9:38
  • 1
1

The following is a variation on your script:

#!/bin/sh

mkdir -p "done"

for file in ./*.tar.gz ./*.zip; do
    printf 'Press Enter to process %s, or Ctrl+C to quit\n' "$file"
    read bogus

    tmpdir=$(mktemp -d)

    printf 'Decompressing %s into %s\n' "$file" "$tmpdir"
    case $file in
        *.tar.gz) tar -xz -f "$file" -C "$tmpdir" ;;
        *.zip)    unzip      "$file" -d "$tmpdir" ;;
    esac

    (
        cd "$tmpdir"
        # do work here

    )

    rm -rf "$tmpdir"
    mv "$file" "done"
done

It iterates over all .tar.gz and .zip files in the current directory. For each file, a temporary extraction directory is created using mktemp -d and the file is extracted into it with tar or unzip depending on the filename suffix.

The subshell around the cd and whatever else you need to do to the extracted data allows you to skip changing directories back to where you started (the changed working directory is local to the subshell).

I suppose the main thing here is the case ... esac statement. This is a way to do different things depending on what pattern a string matches.

See also:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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