gpt4 book ai didi

BASH 脚本 - 删除早于 X 天的文件夹,但部分和所有子文件夹/文件除外

转载 作者:行者123 更新时间:2023-11-29 09:42:28 27 4
gpt4 key购买 nike

我实际上是在测试这个脚本

find /Path/Folder/* -type d -mtime +7 ! -path "/Path/Folder/NODELETE1/*"  ! -path "/Path/Folder/NODELETE2/*"  ! -path "/Path/Folder/NODELETE3/*" -exec rm -rf {} \;

删除所有超过 7 天的文件/文件夹,NODELETE1NODELETE2NODELETE3 文件夹除外。

问题是它显然不起作用,因为它会删除这些文件夹和其中的所有文件。

这就是我想要做的:

我有

/Path/Folder/NODELETE1/some files and folders
/Path/Folder/NODELETE2/some files and folders
/Path/Folder/NODELETE3/some files and folders
/Path/Folder/AFOLDER/somefiles and folders
/Path/Folder/ANOTHERFOLDER/somefiles and folders
/Path/Folder/...
/Path/Folder/FILE
/Path/Folder/ANOTHERFILE
/Path/Folder/...

我想自动删除所有超过 7 天的文件和文件夹(所以 FOLDERANOTHERFOLDER... FILE, ANOTHERFILE, ...) 这样

/Path/Folder/NODELETE1/some files and folders
/Path/Folder/NODELETE2/some files and folders
/Path/Folder/NODELETE3/some files and folders

脚本有什么问题?

使用脚本建议进行编辑:

#!/bin/bash

while IFS= read -r -d '' dir
do

# This line actually halts the control from entering if
# dirname contains either of the three names below. You could
# remove it and put your actual folder names.

[[ $dir =~ ^(NODELETE1|NODELETE2|NODELETE3)$ ]] && continue

# Suggest un-commenting the echo line below and comment rm to ensure
# you have only the folders you want to delete.
echo "$dir"

# rm -rf "$dir"
done< <(find /Users/Username/Desktop/test/* -type d -mtime +7 -print0)

为了测试,我有:

/Users/Username/Desktop/test/NODELETE1
/Users/Username/Desktop/test/NODELETE2
/Users/Username/Desktop/test/NODELETE3
/Users/Username/Desktop/test/YESDELETE

和脚本路径

/Users/Username/Desktop/TEST.sh

最佳答案

TL;DR 修复:

代替你的行,做:

find /Path/Folder/* -type d -mtime +7 ! -path "/Path/Folder/NODELETE1"  ! -path "/Path/Folder/NODELETE2"  ! -path "/Path/Folder/NODELETE3" -exec rm -rf {} \;

更长的解释:

您行中的 -type d 部分仅搜索目录。但是您要排除的是 NODELETE 目录中的内容。这仍然意味着您的 NODELETE 目录是 rm -rf 的目标,因此它们会被递归删除。

关于BASH 脚本 - 删除早于 X 天的文件夹,但部分和所有子文件夹/文件除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341085/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com