Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RAR TO ZIP
#!/bin/sh
#
# rar2zip.sh
# Transforms a single RAR file,
# passed under cmdline,
# to an equivalent ZIP file,
# storing it in the current directory
#
# Typical usage: rar2zip.sh infile.rar
#
# set -ex
function usage
{
cat <<EOF
Usage: rar2zip.sh infile.rar [-f] [-o outfile.zip]
Modifies a RAR file to a ZIP file
Options:
-f force continuation (e.g. if RAR file is damaged)
-o outfile Destination file (defaults to same filename as application, with .zip extension)
-- Break cmdline parsing (useful if the filename starts with -)
EOF
}
function cleanup
{
echo "Cleaning $1.."
rm -rfv $1
}
trap 'cleanup $TMPDIR' 2 15
CWD=$(pwd)
TMPDIR=$(mktemp -d -p /tmp/ rar2zip.XXXXXX)
if [ "$TMPDIR" = "" ]
then
echo "Error creating temporary dir!"
exit 1
fi
# Parse cmdline args
while :
do
case $1 in
-o)
OUTFILE=$2
shift 2
;;
-f)
FORCE=1
shift 1
;;
--)
shift 1
break
;;
*)
echo "A fix to it in the future!"
break
;;
esac
done
if [ "$1" = "" ]
then
usage
cleanup $TMPDIR
exit 1
fi
DEFAULT_ZIP_OPT="-v -9 -b /tmp/"
ZIP_OPT=${ZIP_OPT:-$DEFAULT_ZIP_OPT}
FILE_NAME=$1
BASE_NAME=$(basename $1)
DIR_NAME=$(dirname $1)
# If the target name doesn't start with /,
# it is NOT the 'absolute' pathname --
# It is needed (or something equivalent)
if [ "$(echo $DIR_NAME|grep -c -e'^/' )" = "0" ]
then
DIR_NAME=${CWD}/${DIR_NAME}
fi
ZIP_NAME=$(echo $BASE_NAME|sed -e's/\.[a-zA-Z0-9]\{1,\}$/\.zip/g')
if [ "$(file $DIR_NAME/$BASE_NAME|grep -c -e'RAR archive')" != "1" ]
then
echo "The file $DIR_NAME/$BASE_NAME doesn't appear to be a RAR archive!"
cleanup $TMPDIR
exit 1
fi
cd $TMPDIR
rm -fr ${BASE_NAME}-dir
mkdir -p ${BASE_NAME}-dir
cd ${BASE_NAME}-dir
7z x $DIR_NAME/$BASE_NAME ||
{
if [ "FORCE" != "yes" ]
then
echo "The file $TARGET_NAME/$BASE_NAME appears to be damaged. I will stop now!"
exit 1
else
echo "The file $TARGET_NAME/$BASE_NAME appears to be damaged. I will continue anyway..."
fi ;
}
#Zip the directory contents
find . -type f| sort | zip -@ $ZIP_OPT $ZIP_NAME
mv -- $ZIP_NAME $CWD
rm -fr $TMPDIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.