Create a Linux Recycle Bin with a Simple Shell Script
Learn how to build a custom recycle bin on Linux using a Bash script that moves deleted files to a timestamped folder, includes user confirmation, sets proper permissions, schedules automatic cleanup with cron, and can even replace the rm command via an alias.
Script Code
# vim /bin/delete
#! /bin/bash
[ ! -d /.recycle ] && mkdir -v /.recycle && chmod 777 /.recycle
if [ $# -eq 0 ]; then
echo "Usage: delete file1 [file2 file3...]" && exit 6
fi
read -p "Are you sure you want to delete it? [Y/N]: " action
case $action in
y) ;;
Y) ;;
*) exit ;;
esac
for file in "$@"; do
now=`date +%Y-%m-%d-%H:%M:%S`
newfile=`basename $file`
mv $file /.recycle/${newfile}.$now && echo "$file is deleted!"
doneScript Explanation
1) The script is placed in /bin as delete so users can call it directly.
2) It creates a hidden recycle directory /.recycle with permission 777 if it does not already exist.
3) If no arguments are supplied, it prints a usage message and exits.
4) It prompts the user for confirmation, similar to a Windows dialog.
5) Based on the answer, the script either proceeds or exits.
6) Each specified file is renamed with a timestamp and moved to /.recycle. The script uses $@ for all arguments and basename to strip the path.
Set Executable Permission
# chmod +x /bin/deleteSchedule Automatic Cleanup
Add a weekly cron job to empty the recycle bin:
0 0 * * 0 rm -rf /.recycleTesting
Run the delete command on a file; the file is moved to /.recycle with a timestamp.
Optional Alias
To replace rm with the new script, add the following line to ~/.bashrc and reload: alias rm='sh /bin/delete' Then run source ~/.bashrc to apply immediately.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
