Newer
Older
trm / trm.sh
#!/bin/sh
# trm.sh - Safer 'rm'
# Copyright (c) 2016 TundraWare Inc., Des Plaines, IL USA
# All Rights Reserved
# Permission granted for the free use of this program without restriction

export GRAVEYARD="${HOME}/.graveyard"
mkdir -p $GRAVEYARD

# This function is called at the bottom of this file or it can
# be embedded in a shell startup script.

trm()
{

  # Parse command line args

  OPERATOR="mv"    # Can be overriden with -c option
  OPTLIST='ctdv'   # List of all legal options
  OPTIND=1         # getopts may have been previously used in this context
  TESTMODE=""
  VERBOSE=""

  while getopts ${OPTLIST} opt
  do
    case $opt
    in

      # Copy, don't move, targets to graveyard
      c)
        OPERATOR="cp -pr"
      ;;

      # Empty the graveyard
      d)
        rm -rf  ${VERBOSE} ${GRAVEYARD}/* ${GRAVEYARD}/.[-z]*
      ;;

      # Don't do anything, just show what you would do
      t)
        TESTMODE="testmode"
      ;;

      # Be noisy
      v)
        VERBOSE="-v"
      ;;

      *)
        echo "usage: trm.sh -${OPTLIST}  [file|directory] ..."
        exit 1
      ;;
    esac
  done

  # Process arguments

  shift $((OPTIND-1))
  for arg in $*
  do
      REALPATH=$(readlink -f $arg)
      SRCDIR=$(dirname $REALPATH)
      SRCFIL=$(basename $REALPATH)
      DESDIR=${GRAVEYARD}${SRCDIR}
      SERIAL=$(date +%Y%m%d%s%N)
      DESFIL="${SRCFIL}.${SERIAL}"

      CMD="${OPERATOR} $VERBOSE '${REALPATH}' '${DESDIR}/${DESFIL}'"

      if [ -n "${TESTMODE}" ]
      then
        echo ${CMD}
      else
        mkdir -p ${DESDIR}
        eval ${CMD}
      fi

  done

}

trm $*