trash.sh/trash.sh

56 lines
1.5 KiB
Bash
Raw Normal View History

#!/bin/bash
# Trash Functions
2021-09-21 20:35:16 +02:00
TRASH_DIR="$HOME"/.trash
[ ! -d "$TRASH_DIR" ] && mkdir "$TRASH_DIR"
FILE_PATHS_FILE="$TRASH_DIR/.filepaths"
2021-09-21 18:24:38 +02:00
[ ! -f "$FILE_PATHS_FILE" ] && touch "$FILE_PATHS_FILE"
2021-09-21 18:24:38 +02:00
trash_list() {
2021-09-21 20:35:16 +02:00
find "$TRASH_DIR" ! -name ".filepaths" | tail -n +2
}
2021-09-21 18:24:38 +02:00
trash_put() {
2021-09-21 18:53:48 +02:00
for FILE in $@; do
# Store old filepath for later restore
echo "$FILE $(readlink -f "$FILE")" >>"$FILE_PATHS_FILE"
done
2021-09-21 20:35:16 +02:00
mv -v $* "$TRASH_DIR/"
}
2021-09-21 18:24:38 +02:00
trash_empty() {
2021-09-21 20:45:25 +02:00
echo "Delete $(find "$TRASH_DIR" ! -name ".filepaths" | tail -n +2 | wc -l) files in trash"
2021-09-21 20:44:43 +02:00
\rm -rf "${TRASH_DIR:?}/"* && echo >"$FILE_PATHS_FILE"
}
2021-09-21 18:24:38 +02:00
trash_restore() {
for FILE_TO_RESTORE in "$@"; do
2021-09-21 18:53:48 +02:00
# Get old filepath for restore
OLD_PATH=$(grep "$FILE_TO_RESTORE" "$FILE_PATHS_FILE" | cut -d ' ' -f2)
2021-09-21 18:53:48 +02:00
# Move file to old filepath
2021-09-21 20:35:16 +02:00
mv -v "${TRASH_DIR}/${FILE_TO_RESTORE}" "$OLD_PATH"
2021-09-21 18:53:48 +02:00
# Replace / with \/ from string and remove filepath from file after move was successful
sed -i "/${FILE_TO_RESTORE////\\/}/d" "$FILE_PATHS_FILE"
done
}
2021-09-21 18:24:38 +02:00
trash_rm() {
2021-09-21 18:53:48 +02:00
for FILE_TO_REMOVE in "$@"; do
if ! echo "$FILE_TO_REMOVE" | grep "$HOME/.trash"
2021-09-21 20:05:03 +02:00
then FILEPATH_TO_REMOVE="$HOME/.trash/$FILE_TO_REMOVE"
else FILEPATH_TO_REMOVE="$FILE_TO_REMOVE"
2021-09-21 19:21:19 +02:00
fi
2021-09-21 20:05:03 +02:00
if [ -f "$FILEPATH_TO_REMOVE" ]; then
2021-09-21 20:15:30 +02:00
\rm -irf "$FILEPATH_TO_REMOVE" && sed -i "/$FILE_TO_REMOVE/d" "$FILE_PATHS_FILE"
2021-09-21 18:53:48 +02:00
else
echo "$FILE_TO_REMOVE is not in Trash." && false
fi
done
}
2021-09-21 18:24:38 +02:00
alias trash='trash_put'
alias rm='echo "This is not the command you are looking for. Use \rm instead"; false'