Modify the user's environment variables
VI ~/. BASHRC Note the alias of line 5th #alias RM='rm-i'The last line adds the following content mkdir-P ~/. Trash alias RM=Trash alias R=Trash alias RL='ls ~/.trash'alias ur=undelfile Undelfile () {MV-I ~/.trash/[email protected].} trash () {MV [email protected]~/.trash/} cleartrash () {Read-P"Clear sure? [N]"Confirm [$confirm=='y'] || [$confirm = ='Y'] &&/BIN/RM-RF ~/.trash/* }
Reload Environment variables
SOURCE ~/.BASHRC
Use the command ll-a to view the directory and find more directories. Trash, this directory is used to delete files
Drwxr-xr-x. 2 root root 4096 June 4: Trash
Delete a file
[[Email protected] ~]# RM percona-xtrabackup_2. 2.3. orig.tar.gz
View directory, find deleted files in Recycle Bin directory
[email protected] ~]# LL. trash/33780134584359 June 2: percona-xtrabackup_2. 2.3. orig.tar.gz
If you need to empty the Recycle Bin file, use the following command
[Email protected] ~]# cleartrashclear sure? [N]y
Check again and find it empty.
[email protected] ~]# LL. trash/0
Although RM is defined with an alias, it can be deleted with an absolute path such as/bin/rm 1.txt
It is not saved to the. Trash directory.
Write a script if you need to define automatic cleanup of deleted files for 7 days
If you want all users to be able to use, you can put the global variable configuration
vi/etc/Profile last line add mkdir-P ~/. Trash alias RM=Trash alias R=Trash alias RL='ls ~/.trash'alias ur=undelfile Undelfile () {MV-I ~/.trash/[email protected].} trash () {MV [email protected]~/.trash/} cleartrash () {Read-P"Clear sure? [N]"Confirm [$confirm=='y'] || [$confirm = ='Y'] &&/BIN/RM-RF ~/.trash/* }
Reload Environment variables
Source/etc/profile
Create a normal user test
Useradd A
Set Password
passwd A
Login Linux
View the directory and discover the. Trash directory that is created
[email protected] ~]$ LL-Atotal -drwx ——.3A A4096June4 One: $. DRWXR-xr-x.5Root root4096June4 One: - ..-rw-r–r–.1A A -Oct - the. Bash_logout-rw-r–r–.1A A176Oct - the. Bash_profile-rw-r–r–.1A A124Oct - the. BASHRCDRWXRWXR-X.2A A4096June4 One: $. Trash
Create an empty file
1. txt
deleting files
1. txt
View the Recycle Bin directory and find one more file
[email protected] ~]$ LL. trash/010 June 4: 1. txt
If you feel uncomfortable with the. Trash directory location, you can modify the environment variables, change to other locations, and ensure that the directory is writable.
--------------------------------------------------------------------------------------------------------------- ----------------------------------------------------
If you don't think it's good enough to write. Please look at this article, write your own script more humane, our company adopts this method:
http://www.ibm.com/developerworks/cn/linux/1410_licy_linuxtrash/
Paste it here for easy viewing:
Overview
Deletion is an operation with high risk factors, which can cause an unpredictable loss if deleted by mistake. This danger is particularly noticeable in Linux systems, a simple statement: RM–RF/* will remove the entire system, and Linux will not refuse to execute because of the unreasonable statement. In Windows, the system provides the Recycle Bin function in order to prevent accidental deletion. After the user performs the delete operation, the file is not deleted directly from the hard disk, but is placed in the Recycle Bin. Before emptying the Recycle Bin, users can restore the files in the Recycle Bin to their original location if they are found to have been deleted by mistake. While Linux does not provide similar functionality, the DELETE command RM once confirmed execution, the file will be deleted directly from the system, it is difficult to recover.
Back to top of page
Recycle Bin composition
This article uses a total of three scripts to implement the main functions of the Recycle Bin: Delete scripts, Logtrashdir scripts, and Restoretrash scripts. Where the Delete script is the core script, its role is to reseal the RM command. The command will first move the file or directory to the $home/trash directory, relative to the RM's direct deletion. If the user wants to delete the file directly, you can use the-f option, and the delete script directly calls the RM–F command to remove the file from the hard disk. The Logtrashdir script is used to log information about deleted files to a hidden file in the Trash directory. The Restoretrash script is used to restore the files or directories placed in the trash back to the original path. In a Linux system, the three scripts are placed in the/bin/directory and can be used directly with the chmod +x filename given executable permissions. The main sections of each script are described below
Back to top of page
Delete Script Create Directory
First, to create a directory to hold the deleted files, this article in the user root directory $home set up trash directory to store files. The specific code is as follows:
Listing 1. Creating a Recycle Bin directory
Realrm= "/BIN/RM" if [!-D ~/trash] then mkdir-v ~/trash chmod 777 ~/trash fi
As shown above, first determine if the directory is established, if not established, the first time you run the script, create the Trash directory. The variable REALRM stores the location of the RM script for Linux, which is invoked under certain conditions to directly delete files or directories.
Output Help information
The script outputs a brief help message when the user enters only the script name without entering parameters, and the code is as follows:
Listing 2. Output Help information
If [$#-eq 0] then echo "Usage:delete file1 [file2 file3 ...]" echo "If The options contain-f,then the script would exec ' RM ' directly"
As the code shows, the script is formatted as a delete followed by a path to the file or directory to be deleted, separated by a space.
Delete files directly
Some users confirm that files that are invalid and want to be deleted directly should not be placed in the Recycle Bin, but should be deleted directly from the hard drive. The Delete script provides the-F option to perform this operation:
Listing 3. deleting files directly
While getopts "dfiprrvw" opt does case $opt in f) exec $realrm "[email protected]" ;; *) # do nothing ;; Esac done
If the user adds the-F option to the command, the delete script directly calls the RM command to delete the file or directory directly. As shown in the code, all parameters including options are passed to the RM command. So as long as the option includes the option-F to call the RM command, you can use all of RM's features. such as: DELETE–RFV filename equals RM–RFV filename.
User interaction
You need to confirm with the user whether to put the file in the Recycle Bin. The equivalent of Windows pop-up prompt to prevent users from doing wrong.
Listing 4. User interaction
Echo-ne "is you sure do want to move the files to the trash?" [y/n]:\a "Read replyif [$reply =" Y "-o $reply =" Y "] then #####
Determine file types and delete files larger than 2G directly
This script only operates on normal files and directories, and other types of files are not processed. First, each parameter loop, determine their type, for the type of conformance to determine whether their size is more than 2G, if it is directly removed from the system, to avoid the Recycle Bin occupies too much hard disk space.
Listing 5. deleting files larger than 2G
For file in [email protected] doif [-F "$file" –o–d "$file"]thenif [-F "$file"] && [' ls–l $file |awk ' {print $ "-GT 2147483648] then echo" $file size was larger than 2g,will be deleted directly " ' RM–RF $file ' elif [ -D "$file" && [' du–sb $file |awk ' {print $} '-gt 2147483648] then echo "The directory: $file is larg Er than 2g,will be deleted directly " ' RM–RF $file '
As shown in the preceding code, the script uses different commands to determine the size of the directory and the file. Since the size of the directory should be the total size of the files and subdirectories involved, the ' DU-SB ' command is used. In both cases, awk is used to obtain the value of a particular output field for comparison.
Move files to Recycle Bin and make records
This section is the main part of the Delete script, which mainly accomplishes the following functions
- gets the file name of the parameter. Because the user-specified parameter may contain a path, the parameter from which to get the file name to generate the MV operation. The script uses the string regular expression ' ${file##*/} ' to obtain.
- to generate a new file name. Add a datetime suffix in the original file name to generate a new file name so that when users browse the Recycle Bin, the deletion date for each file is clear. The
- generates an absolute path to the deleted file. The absolute path is generated from the relative path and logged for possible subsequent recovery operations on the deleted file. There are three possible parameters for user input: Only the relative path of the file name, the relative path of the point number, and the absolute path, and the script uses string processing to judge three cases and handle them accordingly.
- calls the Logtrashdir script to log the new file name in the Recycle Bin, the original file name, the deletion time, the original file absolute path to the hidden file
- to move the files through the MV command to the Trash directory. The
Detailed code looks like this:
listing 6. Move files to Recycle Bin and make records now= ' date +%y%m%d_%h_%m_%s ' filename= ' ${file##*/} ' Newfilename= "${file##*/}_${now}" mark1= "." Mark2= "/" If ["$file" = ${file/$mark 2}] then Fullpath= "$ (PWD)/$file" elif ["$file"! = ${file/$mark 1}] then fullpath= " $ (PWD) ${file/$mark 1} "Else fullpath=" $file "fi echo" the full path of this file is: $fullpath "if mv-f $file ~/trash/$ne Wfilename then $ (/logtrashdir "$newfilename $filename $now $fullpath") echo "files: $file is deleted" Else echo "the O Peration is failed "fi
Back to top of page
Logtrashdir Script
The script is simple, is only a simple file write operation, the reason is separate as a script, for later expansion of the convenience, the specific code is as follows:
Listing 7.logTrashDir Code
if [!-F ~/trash/.log] then touch ~/trash/.log chmod 700~/trash/.logfi echo $ $4>> ~/trash/ . log
The script first creates a. log hidden file and then adds a record of the deleted file to it.
Back to top of page
Restoretrash Script
The script mainly accomplishes the following functions:
- Locate the record for the file that the user wants to recover from the. log file. Awk is still used here, and a row containing the deleted file name is found with a positive expression match
- Find the field that records the original file name from the record to prompt the user
- Move the files in the Recycle Bin to their original location, where the mv–b move file is used, and the-B option is added to prevent the original location from having the same name file.
- Delete the record in the. log file that corresponds to the recovered file
Listing 8. Getting the corresponding record
originalpath=$ (awk/$filename/' {print $4} ' "$HOME/trash/.log")
Listing 9. Find the original filename and the current file name field
filenamenow=$ (awk/$filename/' {print $} ' ~/trash/.log) filenamebefore=$ (awk/$filename/' {print $} ' ~/trash/.log) echo "Original name is $filenamebefore" echo "Original path is $originalPath" for about to restore $filenameNow
Listing 10. Restore the file to its original location and delete the corresponding record
echo "is sure to does that?" [y/n] " read reply if [$reply =" Y "] | | [$reply = "Y"] then$ (mv-b "$HOME/trash/$filename" "$originalPath") $ (sed-i/$filename/' d ' "$HOME/trash/.log") else echo "No Files restored " fi
Back to top of page
Automatic periodic cleanup of trash directories
Because the delete operation is not really delete the file, but the move operation, after a period of accumulation, the Trash directory may occupy a lot of hard disk space, resulting in waste of resources, so regular automatic cleanup of files under the Trash directory is necessary. The cleanup rule in this article is that files and directories that exist in the Recycle Bin for more than 7 days will be automatically deleted from the hard disk. The tool used is the crontab that comes with Linux.
Crontab is a command that Linux uses to execute programs on a regular basis. This task dispatch command is started by default when the operating system is installed. The Crontab command periodically checks to see if there is work to be done and the work is performed automatically if there is work to be done. Linux task scheduling is mainly divided into the following two categories:
1, the system performs the work: the system periodically to perform the work, such as the backup system data, cleans up the cache
2, Personal work: a user to do regular work, such as every 10 minutes to check the mail server for new letters, these work can be set by each user.
First write the script Cleantrashcan to be called when Crontab executes. As shown in Listing 10, the script performs two main functions:
- Determine if the file in the Recycle Bin has been stored for more than 7 days and is removed from the Recycle Bin if it is exceeded.
- Deletes the deleted file in the. log file, keeping the data valid and improving the search efficiency.
Listing 11. Delete the files that exist in the Recycle Bin for more than 7 days and delete the corresponding records in the. log
Arraya= ($ (Find ~/trash/*-mtime +7 | awk ' {print $} ')) for file in ${arraya[@]} do $ (rm-rf "${file}") fi Lename= "${file##*/}" echo $filename $ (sed-i/$filename/' d ' "$HOME/trash/.log") done
After the script is written, it is given permission to execute through the chmod command, and then the Crontab–e command is added to add a new task schedule:
Ten * * * */bin/cleantrashcan
The statement means that the Cleantrashcan script is executed at 6:10 P.M. every day
By this task scheduling, the size of the trash will be effectively controlled, will not continue to increase and affect the user's normal operation.
Back to top of page
Practical application
The first thing to do is to put the delete script, Logtrashdir script, Restoretrash script and Cleantrashcan into the/bin directory, then chmod +x Delete Restoretrash logtrashdir The Ntrashcan command gives these three scripts permission to execute.
Delete the file using the delete script, for example to delete the useless file in the/usr directory. Depending on where the user is currently located, parameters can be specified using relative or absolute paths, such as delete Useless,delete./useless or delete/usr/useless. Perform procedure 1 as follows:
Figure 1.delete Script Execution process
After execution, the useless file is removed from the original directory, moved to $home/trash, and renamed, 2.
Figure 2. Recycle Bin directory
The generated. Log record 3. Shows:
Figure 3.log Recording
If the user finds the file to be useful within seven days, you can use the Restoretrash command to restore the deleted file to the original path: Restoretrash ~/trash/useless_20140923_06_28_57. As shown in the specific implementation scenario 4:
Figure 4.restoreTrash Script Execution status
To view the/usr directory, you can find that the useless file has been restored.
Figure 5.useless File is restored
How to set up the Recycle Bin on Linux