Script "remove-archive-contents.sh"
#!/bin/sh

# ----------------------------------
# remove-archive-contents.sh
# version 1.1.0.6
# ----------------------------------

# sorts stdin by length of line
sortlines()
{
  cat - | awk '{print length"\t"$0}' | sort -n -r | cut -f2-
}

remove_if_file()
# parameters: file names
{
  for f_name in $@
  do
    if [ -f "${f_name}" ] || [ -L "${f_name}" ]
    then
      echo "removing file:" "${f_name}"
      rm "${f_name}"
    fi
  done
}

remove_if_empty_dir()
# parameters: empty dir names
{
  for d_name in $@
  do
    if [ -d "${d_name}" ]
    then
      echo -n "removing directory:" "${d_name}"
      rmdir "${d_name}" 2>/dev/null
      [ $? -eq 0 ] && echo " (ok)"
      [ $? -eq 0 ] || echo " (not empty; untouched)"
    fi
  done
}

if [ $# -lt 1 ]
then
  echo "Please specify the name of the archive (for example: ~/path/to/archive.tar.gz)."
  exit 1
fi

ARCHNAME=${1}
if [ ! -f "${ARCHNAME}" ]
then
  echo "${ARCHNAME}: file not found"
  exit 1
fi

# check for required binaries
REQD_BINS=""
which tar >/dev/null 2>&1 || type tar >/dev/null 2>&1 || REQD_BINS="tar,${REQD_BINS}"
which grep >/dev/null 2>&1 || type grep >/dev/null 2>&1 || REQD_BINS="grep,${REQD_BINS}"
which file >/dev/null 2>&1 || type file >/dev/null 2>&1 || REQD_BINS="file,${REQD_BINS}"
which awk >/dev/null 2>&1 || type awk >/dev/null 2>&1 || REQD_BINS="awk,${REQD_BINS}"
if [ ! -z "${REQD_BINS}" ]; then
  echo -e `basename ${0}`: "Required binaries (${REQD_BINS}\010) are not present."
  exit 1
fi

ARCH_CONTENTS=""
ISBZIP2=`file "${ARCHNAME}" | grep bzip2`
ISGZIP=`file "${ARCHNAME}" | grep gzip`

echo -n "Archive type: "
if [ ! -z "${ISBZIP2}" ]
then
  echo "bzip2"
  ARCH_CONTENTS=`tar tjf "${ARCHNAME}"`
elif [ ! -z "${ISGZIP}" ]
then
  echo "gzip"
  ARCH_CONTENTS=`tar tzf "${ARCHNAME}"`
else
  echo "(unknown)"
fi

if [ -z "${ARCH_CONTENTS}" ]
then
  echo "${ARCHNAME}: unsupported archive type. Abort."
  exit 1
fi

NUM_OF_FILES_DIRS=`echo "${ARCH_CONTENTS}" | wc -l`
echo "There are" ${NUM_OF_FILES_DIRS} "files and directories listed in the archive."
echo "Removing the contents of" \'${ARCHNAME}\' "from the current directory" "(`pwd`/)."

echo "Removing files:"
echo "${ARCH_CONTENTS}" | while read LINE
do
  remove_if_file "${LINE}"
done
echo "Done!"

ARCH_CONTENTS=`echo "${ARCH_CONTENTS}" | sortlines`
echo "Removing directories:"
echo "${ARCH_CONTENTS}" | while read LINE
do
  remove_if_empty_dir "${LINE}"
done
echo "Done!"
Unless otherwise stated, the content of this page is licensed under GNU Free Documentation License.