How to set the recycle bin in linux and in linux
Modify user environment variables
Vi ~ /. Comment out the alias of row 5th in bashrc # alias rm = 'rm-I 'and add the following content in the last line: mkdir-p ~ /. Trash alias rm = trash alias r = trash alias rl = 'ls ~ /. Trash 'Alias ur = undelfile () {mv-I ~ /. Trash/$ @./} trash () {mv $ @~ /. Trash/} cleartrash () {read-p "clear sure? [N] "confirm [$ confirm = 'y'] | [$ confirm = 'y'] &/bin/rm-rf ~ /. Trash /*}
Reload Environment Variables
source ~/.bashrc
Run the ll-a command to view the Directory and find that the directory is missing. trash, which is used to exist the deleted file.
drwxr-xr-x. 2 root root 4096 Jun 4 11:31 .trash
Delete an object
[root@localhost ~]# rm percona-xtrabackup_2.2.3.orig.tar.gz
View the Directory and find the deleted file in the recycle bin directory.
[root@localhost ~]# ll .trash/total 33780-rw-r–r–. 1 root root 34584359 Jun 2 09:39 percona-xtrabackup_2.2.3.orig.tar.gz
To clear the recycle bin file, run the following command:
[root@localhost ~]# cleartrashclear sure?[n]y
Check again and find that it is empty.
[root@localhost ~]# ll .trash/total 0
Although rm is defined by an alias, it can be an absolute path to delete files such as/bin/rm 1.txt.
It is not saved to the. trash directory.
If you need to define Automatic Cleaning of files deleted for 7 days, you can write a script
If you want to make it available to all users, you can configure global variables.
Add mkdir-p ~ to the last line of vi/etc/profile ~ /. Trash alias rm = trash alias r = trash alias rl = 'ls ~ /. Trash 'Alias ur = undelfile () {mv-I ~ /. Trash/$ @./} trash () {mv $ @~ /. Trash/} cleartrash () {read-p "clear sure? [N] "confirm [$ confirm = 'y'] | [$ confirm = 'y'] &/bin/rm-rf ~ /. Trash /*}
Reload Environment Variables
source /etc/profile
Create common user test
useradd a
Set Password
passwd a
Log on to Linux
View the Directory and create the. trash directory.
[a@localhost ~]$ ll -atotal 24drwx——. 3 a a 4096 Jun 4 11:45 .drwxr-xr-x. 5 root root 4096 Jun 4 11:44 ..-rw-r–r–. 1 a a 18 Oct 16 2014 .bash_logout-rw-r–r–. 1 a a 176 Oct 16 2014 .bash_profile-rw-r–r–. 1 a a 124 Oct 16 2014 .bashrcdrwxrwxr-x. 2 a a 4096 Jun 4 11:45 .trash
Create an empty file
[a@localhost ~]$ touch 1.txt
Delete an object
[a@localhost ~]$ rm 1.txt
View the recycle bin directory and find an additional file.
[a@localhost ~]$ ll .trash/total 0-rw-rw-r–. 1 a a 0 Jun 4 11:45 1.txt
If you are uncomfortable with the. trash directory location, you can modify the environment variable and change it to another location. Ensure that the directory is writable.
Certificate -------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you think this writing is not good enough. Please read this article and write your own scripts more user-friendly. Our company adopts this method:
Http://www.ibm.com/developerworks/cn/linux/1410_licy_linuxtrash/
Paste it here for ease of viewing:
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.
Back to Top
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.
Back to Top
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 itnow=`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
Back to Top
LogTrashDir script
This script is simple. It is only a simple file write operation. It is used as a script separately for convenience of future extension. The specific code is as follows:
Listing 7. logTrashDir code
if [ ! -f ~/trash/.log ] then touch ~/trash/.log chmod 700~/trash/.logfi echo $1 $2 $3 $4>> ~/trash/.log
This script first creates a. log hidden file, and then adds the records for deleting the file to it.
Back to Top
RestoreTrash script
This script provides the following functions:
- Find the record of the file you want to restore from the. log file. Awk is still used here, and a row containing the deleted file name is found through positive expression matching.
- Find the field that records the original file name from the record to notify the user
- Move the files in the recycle bin to the original location and use mv-B to move the files here. The-B option is added to prevent files with the same name in the original location.
- Delete records corresponding to the recovered files in the. log File
Listing 8. Getting corresponding records
originalPath=$(awk /$filename/'{print $4}' "$HOME/trash/.log")
Listing 9. Search for the original file name and current file name fields
filenameNow=$(awk /$filename/'{print $1}' ~/trash/.log)filenamebefore=$(awk /$filename/'{print $2}' ~/trash/.log)echo "you are about to restore $filenameNow,original name is $filenamebefore"echo "original path is $originalPath"
Listing 10. Restore the file to its original location and delete the corresponding records
echo "Are you sure to do 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
Automatically clear the trash directory regularly
Because the delete operation does not actually delete files, It is a mobile operation. After a period of accumulation, the trash directory may occupy a large amount of hard disk space, resulting in a waste of resources, therefore, regular and automatic cleanup of files in the trash directory is required. The cleanup rule in this article is: files and directories that have been stored in the recycle bin for more than seven days will be automatically deleted from the hard disk. The tool used is the crontab that comes with Linux.
Crontab is a command used by Linux to regularly execute programs. After the operating system is installed, the task scheduling command is started by default. The Crontab command regularly checks whether there is any job to be executed. If there is any job to be executed, the job is automatically executed. Linux task scheduling mainly includes the following two types:
1. work performed by the system: work to be performed periodically by the system, such as backing up system data and clearing Cache
2. Personal Work: The work that a user regularly performs, such as checking whether there are new emails on the email server every 10 minutes. This work can be set by each user.
First, compile the cleanTrashCan script to be called during crontab execution. As shown in listing 10, this script mainly provides two functions:
- Determine whether the storage time of files in the recycle bin has exceeded 7 days. If the storage time exceeds 7 days, delete the files from the recycle bin.
- Delete the corresponding records of the deleted file in the. log File to maintain the validity of the data and improve the search efficiency.
Listing 11. delete files that have been in the recycle bin for more than 7 days and delete the corresponding records in. log.
arrayA=($(find ~/trash/* -mtime +7 | awk '{print $1}')) for file in ${arrayA[@]} do $(rm -rf "${file}") filename="${file##*/}" echo $filename $(sed -i /$filename/'d' "$HOME/trash/.log") done
After the script is compiled, run the chmod command to grant it the execution permission, and run the crontab-e command to add a new task scheduling:
10 18 * * * /bin/ cleanTrashCan
The statement indicates that the cleanTrashCan script is executed at 06:10 P.M. every day.
With this task scheduling, the trash size will be effectively controlled and will not continue to increase, thus affecting users' normal operations.
Back to Top
Practical Application
First, put the delete script, logTrashDir script, restoreTrash script, and cleanTrashCan in the/bin directory, and then use the chmod + x delete restoreTrash logTrashDir cleanTrashCan command to grant the three scripts executable permissions.
Use the delete script to delete files, for example, useless files under the/usr directory. You can use relative or absolute paths to specify parameters based on your current location, such as delete useless, delete./useless, or delete/usr/useless. Execution Process 1:
Figure 1. delete Script Execution Process
After execution, the useless file will be deleted from the original directory, moved to $ HOME/trash, and renamed, as shown in 2:
Figure 2. recycle bin directory
The generated. log record 3. is shown as follows:
Figure 3.log record
If the user finds that the file is still 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. Execution 4:
Figure 4. restoreTrash Script Execution
View the/usr directory and you can find that the useless file has been restored to this point.
Figure 5. useless file recovered