linux 替换rm命令为移动到固定文件夹
痛定思痛之后,写个教程教大家直接把rm给换成mv,这样就不会彻底删除找不到了。
首先把rm的意义重定向。
> vi ~/.bashrc
#加入这么一行在bashrc中
alias rm='/home/rm_replace.sh'
#退出~/.bashrc后更新
> source ~/.bashrc
#检查是否已经重定向
> which rm
如果显示了这行说明就对了。

拟实现的代码目的和功能:
当rm时,需要输入y确认
输入y确认删除后,也只是将文件或目录移动到指定垃圾箱目录下,假装删除,并保存移动的log文件到垃圾箱目录中。
当指定目录已有同名文件,将新移入的文件加上时间后缀。
无论是删除目录还是文件,都只需要rm,而不需要rm -rf。
注意:如果你完全看不懂下面的代码,说明你不适合做这项操作。别搞。
定义rm_replace.sh
#!/bin/bash
# Define trash directory
TRASH_DIR="$HOME/Trash_for_rm"
# Create trash directory if it does not exist
if [[ ! -d "$TRASH_DIR" ]]; then
mkdir -p "$TRASH_DIR"
fi
# Create log file in trash directory
LOG_FILE="$TRASH_DIR/trash_log_$(date +%Y%m%d_%H%M%S).txt"
touch "$LOG_FILE"
# Confirm deletion with user
echo "This is a custom rm command. It moves files and directories to the Trash instead of deleting them."
echo "Are you sure you want to continue? [y/n]"
read response
if [[ "$response" =~ ^[Yy]$ ]]; then
for file in "$@"; do
# 获取文件名和路径
filename=$(basename "$file")
filepath=$(dirname "$file")
# 判断目标文件是否存在
if [[ -e "$TRASH_DIR/$filename" ]]; then
# 给文件名加上时间戳,避免文件名冲突
timestamp=$(date +%Y%m%d%H%M%S)
new_filename="${filename}_${timestamp}"
echo "WARNING: file '$filename' already exists in Trash_for_rm, renaming to '$new_filename'."
mv "$file" "$TRASH_DIR/$new_filename"
echo "[$(date +%Y%m%d_%H%M%S)] Directory $file moved to trash." >> "$LOG_FILE"
else
mv "$file" "$TRASH_DIR"
echo "[$(date +%Y%m%d_%H%M%S)] File $file moved to trash." >> "$LOG_FILE"
fi
done
echo "Files and directories moved to Trash_for_rm."
else
echo "Aborted."
fi
实战效果如图所示。

我现在已经想开了。