Linux回收站脚本背景与目标
众所周知,Linux操作系统原生并未内置回收站机制,这使得许多用户在执行删除操作时心存顾虑(尽管资深管理员通常能避免此类失误)。虽然从安全角度建议培养谨慎的操作习惯而非依赖回收站,但针对“101个脚本之#15 Archiving Files As They're Removed”这一主题,我们将重点介绍如何构建一个简易的Linux回收站脚本。
#!/bin/sh
# newrm, a replacement for the existing rm command, provides a
# rudimentary unremove capability by creating and utilizing a new
# directory within the user's home directory. It can handle directories
# of content as well as individual files, and if the user specifies
# the -f flag files are removed and NOT archived.
# Big Important Warning: You'll want a cron job or something similar to keep
# the trash directories tamed. Otherwise nothing will ever actually
# be deleted from the system and you'll run out of disk space!
mydir="$HOME/.deleted-files"
realrm="/bin/rm"
copy="/bin/cp -R"
if [ $# -eq 0 ] ; then # let 'rm' ouptut the usage error
exec $realrm # our shell is replaced by /bin/rm
fi
# Parse all options looking for '-f'
flags=""
while getopts "dfiPRrvW" opt
do
case $opt in
f) exec $realrm "$@" ;; # exec lets us exit this script directly.
*) flags="$flags -$opt" ;; # other flags are for 'rm', not us
esac
done
shift $(($OPTIND - 1))
# Make sure that the $mydir exists
if [ ! -d $mydir ] ; then
if [ ! -w $HOME ] ; then
echo "$0 failed: can't create $mydir in $HOME" >&2
exit 1
fi
mkdir $mydir
chmod 700 $mydir # a little bit of privacy, please
fi
for arg
do
newname="$mydir/$(date "+%S.%M.%H.%d.%m").$(basename "$arg")"
if [ -f "$arg" ] ; then
$copy "$arg" "$newname"
elif [ -d "$arg" ] ; then
$copy "$arg" "$newname"
fi
done
exec $realrm $flags "$@" # our shell is replaced by realrm
该脚本的核心实现思路在于利用Shell别名(alias)机制,将系统默认的rm命令替换为用户自定义的myrm脚本。当用户执行删除指令时,实际运行的是myrm脚本,其功能是将目标文件或目录移动至当前用户主目录下名为.deleted-files的隐藏文件夹中,以此达到类似回收站的效果。
接下来详细解析该脚本的具体代码逻辑与执行流程。
while getopts "dfiPRrvW" opt
do
case $opt in
f) exec $realrm "$@" ;; # exec lets us exit this script directly.
*) flags="$flags -$opt" ;; # other flags are for 'rm', not us
esac
done
脚本中包含对特定选项的处理逻辑:如果用户在使用命令时附带了-f(强制删除)选项,则绕过回收站机制,直接调用原始的rm命令进行彻底删除,确保紧急清理场景下的需求得到满足。
for arg
do
newname="$mydir/$(date "+%S.%M.%H.%d.%m").$(basename "$arg")"
if [ -f "$arg" ] ; then
$copy "$arg" "$newname"
elif [ -d "$arg" ] ; then
$copy "$arg" "$newname"
fi
done
对于常规删除请求,脚本使用for循环遍历所有传入的参数。在循环内部,通过date命令生成包含秒、分、时、日、月的时间戳,并结合basename获取原文件名,构造出唯一的归档名称newname。随后,脚本将文件复制到上述定义的回收站目录中,完成归档操作。