Unlike Windows, deleting files on Linux is put into the recycle bin. If the files are incorrectly deleted, they can be retrieved through the recycle bin. In Linux, the rm -rf command is used to delete files, and the files cannot be retrieved after deletion. This mechanism brings a huge lesson every time. To achieve a recycle bin mechanism to avoid the occurrence of tragedy. The principle is as follows:

  1. The rm command is redirected to move the file to a specific directory without actually deleting it

  2. Set a time to clear the temporary recycle bin periodically

Redirection command

Write a shell script first to replace the rm command, or use the mv command to move the file to the recycle bin when it needs to be deleted

  1. Home directory (~) Create a hidden folder: mkdir.trash

  2. Home directory (~) Create the tool folder to save remove.sh

  3. The script basically renames the file based on the current date and moves it to.trash, as follows

TRASH_DIR="~/.trash"  
for i in $*; do  
  STAMP=`date +%m-%d-%H:%M:%S`  
  fileName=`basename $i`  
  mv $i $TRASH_DIR/$fileName.$STAMP  
done4. Bind the rm command to the remot. sh script. Modify ~/. Bashrc by adding a lineCopy the code

4. Bind the system rm command to the remover. Sh script and add a line to ~/

alias rm="sh ~/tools/remove.sh"Copy the code

  • Alias Sets the alias of the command. This command is equivalent to executing rm and remove.sh

  • Source ~/. Bashrc Makes the replacement take effect immediately

Regularly cleaned

You can run the crontab command to run the specified system commands or shell script scripts at a fixed interval

Run crontab -e to add the command

0 0 * * * rm -rf ~/.trash/*

  • Indicates that the contents of the.tarsh file are deleted at 00:00 every day