Automator Workflow to convert .zip files to .tar.gz files

Inspired by this automator workflow, which zips a file or directory selected in Finder, I’ve written a shell script to convert a .zip file to a .tar.gz file without further intervention. In the case of non-.zip files, it silently skips to the next file.

The easiest thing to do is probably to grab the automator workflow from the linked post, and replace the shell script within with the following bits:


#!/bin/bash

for f in "$@"
do
# If the file doesn't end in .zip, skip this file
ADDZIP=`basename "$f" .zip`.zip
NOADDZIP=`basename "$f"`
[ "$ADDZIP" != "$NOADDZIP" ] && continue

# Figure out the short file name, the name of the tarfile, and
# where we need to put that tarfile
FILENAME="$(basename "$f")"
TARFILE="$(basename "$f" .zip).tar.gz"
TARGETDIR="$(dirname "$f")"

# If the Target directory is "." according to dirname, change that to
# the current directory name (full path)
[ "$TARGETDIR" = "." ] && TARGETDIR="$(pwd)"

# Make a temporary directory into which we can put the contents
# of the .zip file
TEMPDIR="$(mktemp -d /tmp/convertziptotar.XXXXXX)"
cd "$TEMPDIR"

# Unzip that zipfile and re-tar it
unzip -L "$TARGETDIR/$FILENAME"
tar czf "$TARGETDIR/$TARFILE" .

# Leave the temporary directory and delete it
cd "$TARGETDIR"
rm -rf "$TEMPDIR"

done