How to Build a Safe Linux Trash Bin by Aliasing the rm Command
This guide shows how to create a personal recycle bin on Linux by redefining the rm command with Bash aliases and functions, enabling safe file deletion, restoration, and cleanup while explaining each step, the required code, and usage examples.
In Linux the rm command permanently deletes files because the system lacks a built‑in recycle bin, which can lead to accidental data loss, especially when using the force options -f or -rf.
To mitigate this risk you can implement a custom trash can by redefining rm through Bash aliases in the .bashrc file.
Setup steps
vim ~/.bashrcAppend the following lines to the end of the file:
mkdir -p ~/.trash
alias rm=trash
alias r=trash
alias rl='ls ~/.trash/'
alias ur=undelfile
undelfile() {
mv -i ~/.trash/$@ ./
}
trash() {
mv -i $@ ~/.trash/
}
cleartrash() {
read -p "clear sure?[n]" confirm
[ $confirm == 'y' ] || [ $confirm == 'Y' ] && /bin/rm -rf ~/.trash/*
}This creates a hidden .trash directory in your home folder and defines four aliases: rm and r now invoke the trash function, which moves specified files to ~/.trash using the interactive -i option to avoid overwriting. rl runs ls ~/.trash/ to list the contents of the trash. ur calls undelfile, which moves selected files back to the current directory. cleartrash prompts for confirmation and then empties the trash with /bin/rm -rf.
Activate the changes
source ~/.bashrcNow you can safely delete, list, restore, and clear files:
Example workflow
# Create test files
touch file1 file2 file3
# Delete with the new alias
rm file1 file2
r file3
# View trash contents
rl
# Restore files
ur file1
ur file2
ur file3
# Verify restoration
ls
# Empty the trash when needed
cleartrashWhile this custom trash provides a safety net, it is still advisable to maintain regular backups to protect against larger mistakes.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
