Bash script to convert archive to .zip format

bashcompressionrar

I'm looking for a flexible bash script to do the following:

  1. Convert .rar, .tar, .tar.gz, .bz2, .7z archives to .zip format
  2. Keep all folder structures and filenames as source archive.
  3. Convert it quietly, outputs "error" on failure and outputs "encrypted" on password protected archived.

Thanks in advance.

Best Answer

I think you'll want to use a case statement to choose how to unpack the input archive based on the filename (or perhaps use file to base it on the content instead). Unpack the input archive to a temporary directory, piping stdout/stdin to /dev/null or a file. Then run zip on the contents of the temporary directory, saving to a filename provided on the commandline. Remove the temporary directory.

Something like this (UNTESTED):

infile="$1"
outfile="$2"
# Add syntax checking here
tempdir=`mktemp -d`
case "$infile" in
    *.tar.gz)
        tar -C "$tempdir" -xzf "$infile" 2>/dev/null
        ;;
    *.tar)
        tar -C "$tempdir" -xf "$infile" 2>/dev/null
        ;;
... # Add handling for other input formats here
    *)
        echo "Unrecognized input format" >&2
        false
        ;;
esac
if [ $? -ne 0 ]; then
    echo "Error processing input file $infile" >&2 # or just echo "error"
    rm -rf "$tempdir"
    exit 1
fi
(cd "$tempdir" && zip "$outfile" .)
rm -rf "$tempdir"

You'll need to determine what errors you get from tar, etc when an achive is "encrypted", and update the error messages appropriately to match what you're after. But this should give you a reasonable starting point.