linux 防误删机制脚本
2022/4/29 7:13:52
本文主要是介绍linux 防误删机制脚本,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
linux 防误删机制脚本
1.1 背景介绍
linux系统下,经常有运维或者开发误删除,所以写了个脚本,防止误删除操作
简单思路就是创建个隐藏文件夹,用mv脚本替换rm命令
2.1 脚本详情
cat <<'EOF_INSTALL' > /usr/bin/rm_safely.sh #!/bin/bash # Created: Zhaoping.lu, 2021.12 # Purpose: # A replacement for rm command. Will move the target files into ~/.trash/trash_<time_flag> instead "rm". # And the trash folders elder than specified days will be pruged. # Changes # V1, 20211222, Created. KEEP_DAYS=7 #文件保留天数 TRASH_BASE_DIR=$HOME/.trash function usage() { cat <<EOF2022 Usage: rm FILE... Move files into $TRASH_BASE_DIR instead of deleting them. EOF2022 exit 0 } [[ -z $@ || $@ == "-h" || $@ == "--help" ]] && usage CURR_TRASH_DIR=$TRASH_BASE_DIR/trash_$(date +"%Y%m%d_%H%M%S.%N") mkdir -p $CURR_TRASH_DIR [[ $? -ne 0 ]] && "Failed to create trash folder:$CURR_TRASH_DIR. Check disk free space. Quit." && exit 1 MV=/usr/bin/mv RM=/usr/bin/rm # process input arguments, skip command options TARGETS="" for FNAME in $@; do if [[ ! "$FNAME" =~ ^- ]]; then TARGETS=$TARGETS" "$FNAME fi done $MV $TARGETS $CURR_TRASH_DIR # clean trash files older than specified days function delete_elder_than_days() { DAYS=$1 TM_FLAG=$(date +"%Y%m%d_%H%M%S.%N" -d "$DAYS days ago") find $TRASH_BASE_DIR -mindepth 1 -maxdepth 1 -name "trash_*" | awk -v rm_cmd=$RM -v trash_base_dir=$TRASH_BASE_DIR -v tm_flag=$TM_FLAG '{if ($0 < trash_base_dir"/trash_"tm_flag && $0 ~ /trash_/) {system(rm_cmd" -rf \""$0"\"");} }' } delete_elder_than_days $KEEP_DAYS EOF_INSTALL chown root:root /usr/bin/rm_safely.sh chmod 755 /usr/bin/rm_safely.sh echo "alias rm='/usr/bin/rm_safely.sh'" >> /etc/bashrc echo "<Done>"
3.1 脚本部署
脚本特点:
- 将“rm”设置为rm-safely.sh的别名
- 执行rm时,实际上是将文件移动到了$HOME/.trash目录下,同时自动清理超期文件
- 不具备restore命令,需要恢复文件时,直接到$HOME/.trash下找回文件即可
#创建文件/usr/bin/rm_safely.sh chown root:root /usr/bin/rm_safely.sh chmod 755 /usr/bin/rm_safely.sh #仅对bash有效。使用其它shell时,则需要在相应的profile里添加此别名 echo "alias rm='/usr/bin/rm_safely.sh'" >> /etc/bashrc
这篇关于linux 防误删机制脚本的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-22原生鸿蒙操作系统HarmonyOS NEXT(HarmonyOS 5)正式发布
- 2024-10-18操作系统入门教程:新手必看的基本操作指南
- 2024-10-18初学者必看:操作系统入门全攻略
- 2024-10-17操作系统入门教程:轻松掌握操作系统基础知识
- 2024-09-11Linux部署Scrapy学习:入门级指南
- 2024-09-11Linux部署Scrapy:入门级指南
- 2024-08-21【Linux】分区向左扩容的方法
- 2024-08-21【Linux】gnome桌面环境切换KDE Plasma
- 2024-08-19如何安装 VMware Tools (macOS, Linux, Windows)
- 2024-08-15Linux部署Scrapy教程:入门级指南