系统相关
首页 > 系统相关> > linux 防误删机制脚本

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 脚本部署

脚本特点:

#创建文件/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

标签:脚本,bin,误删,sh,usr,linux,rm,trash,safely
来源: https://www.cnblogs.com/liwenchao1995/p/16204501.html