我想删除$DIR_TO_CLEAN超过$DAYS_TO_SAVE几天的文件.简单:
find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)
我想我们可以添加一个-type f或一个-f标志rm,但我真的想计算被删除的文件数量.
我们可以天真地做到这一点:
DELETE_COUNT=`find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE | wc -l`
find "$DIR_TO_CLEAN" -mtime +$DAYS_TO_SAVE -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)
但是这个解决方案还有很多不足之处.除了命令重复之外,如果rm无法删除文件,此代码段会高估计数.
我与重定向体面舒适,管道(包括命名的),子shell, xargs,tee等,但我渴望学习新的技巧.我想要一个适用于bash和ksh的解决方案.
你如何计算删除的文件数量find?
我会避免-exec并采用管道解决方案:
find "$DIR_TO_CLEAN" -type f -mtime +$DAYS_TO_SAVE -print0 \
| awk -v RS='\0' -v ORS='\0' '{ print } END { print NR }' \
| xargs -0 rm
Run Code Online (Sandbox Code Playgroud)
使用awk计数比赛和把它们交给rm.
kojiro让我意识到上述解决方案不计算成功/失败率rm.由于awk命名错误的文件存在问题,我认为以下bash解决方案可能更好:
find "${DIR_TO_CLEAN?}" -type f -mtime +${DAYS_TO_SAVE?} -print0 |
(
success=0 fail=0
while read -rd $'\0' file; do
if rm "$file" 2> /dev/null; then
(( success++ ))
else
(( fail++ ))
fi
done
echo $success $fail
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5062 次 |
| 最近记录: |