Implementation of the recycle bin function in Linux

Source: Internet
Author: User

Implementation of the recycle bin function in Linux

This document describes how to use the Bash script to delete files or directories in Linux based on the Windows recycle bin function. Create a delete script instead of the rm command. This script implements the following functions: directly delete files or directories larger than 2 GB; otherwise, put them in the $ HOME/trash directory; restore the deleted files in the trash directory to the original directory; files are automatically deleted more than seven days after they are stored in the trash directory.

Overview

Deletion is an operation with a high risk factor. accidental deletion may cause incalculable losses. This is especially dangerous in Linux systems. A simple statement: rm-rf/* will delete all the systems, and Linux will not refuse to execute this statement because it is unreasonable. In Windows, the recycle bin function is provided to prevent accidental deletion. After a user deletes a file, the file is not directly deleted from the hard disk, but stored in the recycle bin. Before clearing the recycle bin, if a file is deleted by mistake, you can restore the file in the recycle bin to its original location. Linux does not provide similar functions. Once the DELETE command rm is confirmed to be executed, the file will be deleted directly from the system, which is difficult to restore.

Recycle Bin Composition

This article shares three scripts to implement the main functions of the recycle bin: Delete script, logTrashDir script, and restoreTrash script. The Delete script is the core script, and its role is to re-encapsulate the rm command. This command first moves the file or directory to the $ home/trash directory. If you want to delete a file directly, you can use the-f option. The delete script directly calls the rm-f command to delete the file from the hard disk. The logTrashDir script is used to record the information of the deleted file to a hidden file under the trash directory. The restoreTrash script is used to restore the files or directories in the trash to the original path. In Linux, you only need to put the three scripts in the/bin/directory and grant the executable permission using chmod + X filename. The following describes the main parts of each script.

Delete script to create a directory

First, you must create a directory to store the deleted files. In this article, you will create a trash directory under $ HOME in the user's root directory to store the files. The Code is as follows:

List 1. Create a recycle bin directory
realrm="/bin/rm"if [ ! -d ~/trash ] then      mkdir -v ~/trash      chmod 777 ~/trash fi

As shown above, first determine whether the directory has been created. If not, that is, the first time you run the script, create the trash directory. The variable realrm stores the rm script location in Linux and is used to directly delete files or directories by downgrading specific conditions.

Output help information

When you only enter the Script Name and do not enter a parameter to execute the script, a brief help information is output. The Code is as follows:

List 2. Output help information
if [ $# -eq 0 ]  then      echo "Usage:delete file1 [file2 file3....]"      echo "If the options contain -f,then the script will exec 'rm' directly"

As shown in the Code, the script is in the format of delete followed by the path of the file or directory to be deleted, separated by spaces.

Directly delete an object

Some users confirm that they are invalid and want to delete the files directly. They should not be placed in the recycle bin, but should be deleted directly from the hard disk. The Delete script provides the-f option to perform this operation:

Listing 3. Directly deleting an object
while getopts "dfiPRrvW" opt      do        case $opt in            f)               exec $realrm "$@"                ;;            *)                              # do nothing                     ;;        esac      done

If you add the-f option to the command, the delete script directly calls the rm command to delete the file or directory. As shown in the Code, all parameters, including options, are passed to the rm command. Therefore, if option-f is included in the option, all functions of rm can be used. For example, delete-rfv filename is equal to rm-rfv filename.

User Interaction

You need to confirm with the user whether to put the file into the recycle bin. It is equivalent to a Windows pop-up prompt to prevent user misoperation.

List 4. User Interaction
echo -ne "Are you sure you want to move the files to the trash?[Y/N]:\a" read replyif [ $reply = "y" -o $reply = "Y" ]  then #####
Determine the file type and directly delete files larger than 2 GB

This script only performs operations on common files and directories, and does not process other types of files. Cycle each parameter to determine their type, and then determine whether their size exceeds 2 gb for the conforming type. If so, delete them directly from the system, avoid the recycle bin occupying too much hard disk space.

Listing 5. deleting files larger than 2 GB
for file in $@ doif [ -f "$file" –o –d "$file" ]thenif [ -f "$file" ] && [ `ls –l $file|awk '{print $5}'` -gt 2147483648 ]   then      echo "$file size is larger than 2G,will be deleted directly"        `rm –rf $file`elif [ -d "$file" ] && [ `du –sb $file|awk '{print $1}'` -gt 2147483648 ]   then      echo "The directory:$file is larger than 2G,will be deleted directly"        `rm –rf $file`

As shown in the code above, the script uses different commands to determine the Directory and file size respectively. The 'du-sb 'command is used because the directory size should be the total size of the files and subdirectories. In both cases, awk is used to obtain the value of a specific output field for comparison.

Move the file to the recycle bin and record it

This part is the main part of the Delete script, mainly to complete the following functions

  • Get the parameter file name. Because the specified parameter may contain a path, you need to obtain the file name from it to generate the mv operation parameter. This script uses the string regular expression '$ {file ### */}' to obtain it.
  • Generate a new file name. Add a date and time suffix to the original file name to generate a new file name. This allows you to view the deletion date of each file in the recycle bin.
  • Generate the absolute path of the deleted file. In order to recover the deleted files in the future, you must generate an absolute path from the relative path and record it. User-input parameters may be in three situations: they only contain the relative path of the file name, including the relative path of the dot and absolute path, and the script uses strings to process and judge the three situations, and perform corresponding processing.
  • Call the logTrashDir script to record the new file name, original file name, deletion time, and absolute path of the original file in the recycle bin to the hidden file.
  • Run the mv command to move the file to the Trash directory.

    The detailed code is as follows:

    Listing 6. Move the file to the recycle bin and record it
    now=`date +%Y%m%d_%H_%M_%S`filename="${file##*/}"newfilename="${file##*/}_${now}"mark1="."mark2="/"if  [ "$file" = ${file/$mark2} ] then  fullpath="$(pwd)/$file"elif [ "$file" != ${file/$mark1} ] then  fullpath="$(pwd)${file/$mark1}"else  fullpath="$file"fi    echo "the full path of this file is :$fullpath"if mv -f $file ~/trash/$newfilename then  $(/logTrashDir "$newfilename $filename $now $fullpath")   echo "files: $file is deleted" else  echo "the operation is failed" fi

 

For more details, please continue to read the highlights on the next page:

  • 1
  • 2
  • Next Page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.