Last active
August 29, 2015 14:24
-
-
Save vincepare/6bee5302f98159cea54b to your computer and use it in GitHub Desktop.
Move target (file or directory) to trash folder, keeping directory structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Trash It | |
# Move target (file or directory) to trash folder, keeping directory structure. | |
# This aims to be an ersatz recycle bin. | |
# | |
# Author : Vincent Paré | |
# | |
# Usage: | |
# trashit <trashfolder> <target> | |
# Example : | |
# find . -type d -iname *toDelete* | xargs -I{} trashit .trash {} | |
# Help message | |
usage() { | |
echo "Usage: $0 [trashfolder] [target]" | |
} | |
if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then | |
usage | |
exit | |
fi | |
# Arguments check | |
if [ ! "$1" ] || [ ! "$2" ]; then | |
[ "$1" ] || >&2 echo "Missing arg 1" | |
[ "$2" ] || >&2 echo "Missing arg 2" | |
usage | |
exit 1 | |
fi | |
if [[ "$1" == *".."* ]] || [[ "$2" == *".."* ]]; then | |
>&2 echo '[trashfolder] and [target] cannot contain ".."' | |
exit 2 | |
fi | |
# Checking trash directory | |
if [ ! -d "$1" ]; then | |
>&2 echo "Trash directory does not exists ($1)" | |
exit 3 | |
fi | |
# Checking target | |
if [ ! -d "$2" ] && [ ! -f "$2" ]; then | |
>&2 echo "target ($2) does not exists" | |
exit 4 | |
fi | |
parentdir=`dirname "$2"` | |
trashdir="$1/$parentdir" | |
itemname=`basename "$2"` | |
trashpath="$trashdir/$itemname" | |
# No clobber | |
if [ -d "$trashpath" ] || [ -f "$trashpath" ]; then | |
>&2 echo "Target path already exists into trash ($trashpath)" | |
exit 5 | |
fi | |
# Creating tree into trash | |
if [ ! -d "$trashdir" ]; then | |
mkdir -p "$trashdir" | |
fi | |
# Moving target to trash | |
mv -nv "$2" "$trashdir" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment